1
下面的python代碼的第10行有一個UnboundLocalError。任何人都可以請教我如何解決這個問題?ErrorCode:UnboundLocalError on line 10
def answer(data, n):
new_data = []
for each_integer in data:
new_data = [each_integer for each_integer in data if data.count(each_integer) == n]
if n > 1:
new_data = data
print("\n\nNew Data")
print(new_data)
supplied_data = [53, 85, 29, 23, 29, 26, 88, 78, 5, 75, 74, 44, 33, 62, 98, 50, 89, 93, 24, 14, 74, 49, 83, 45, 41, 14, 68, 76, 68, 8, 77, 85, 17, 3, 9, 30, 71, 48, 18, 25, 86, 55, 55, 20, 74, 76, 99, 87, 59, 87, 36, 29, 29, 8, 22, 65, 1, 18, 23, 5, 13, 60, 7, 5, 98, 61, 78, 64, 36, 60, 49, 57, 31, 32, 41, 86, 52, 90, 9, 55, 35, 35, 2, 44, 8, 19, 96, 81, 68, 7, 8, 51, 9, 76, 12, 96, 61, 99, 74]
answer(supplied_data, 0)
answer(supplied_data, 1)
answer(supplied_data, 6)
回溯
>>> def answer(data, n): ... for each_integer in data: ... new_data = [each_integer for each_integer in data if data.count(each_integer) == n] ... if n > 1: ... new_data = data ... print("\n\nNew Data") ... print(new_data) ... ... supplied_data = [53, 85, 29, 23, 29, 26, 88, 78, 5, 75, 74, 44, 33, 62, 98, 50, 89, 93, 24, 14, 74, 49, 83, 45, 41, 14, 68, 76, 68, 8, 77, 85, 17, 3, 9, 30, 71, 48, 18, 25, 86, 55, 55, 20, 74, 76, 99, 87, 59, 87, 36, 29, 29, 8, 22, 65, 1, 18, 23, 5, 13, 60, 7, 5, 98, 61, 78, 64, 36, 60, 49, 57, 31, 32, 41, 86, 52, 90, 9, 55, 35, 35, 2, 44, 8, 19, 96, 81, 68, 7, 8, 51, 9, 76, 12 , 96, 61, 99, 74] File "", line 9 supplied_data = [53, 85, 29, 23, 29, 26, 88, 78, 5, 75, 74, 44, 33, 62, 98, 50, 89, 93, 24, 14, 74, 49, 83, 45, 41, 14, 68, 76, 68, 8, 77, 85, 17, 3, 9, 30, 71, 48, 18, 25, 86, 55, 55, 20, 74, 76, 99, 87, 59, 87, 36, 29, 29, 8, 22, 65, 1, 18, 23, 5, 13, 60, 7, 5, 98, 61, 78, 64, 36, 60, 49, 57, 31, 32, 41, 86, 52, 90, 9, 55, 35, 35, 2, 44, 8, 19, 96, 81, 68, 7, 8, 51, 9, 76, 12 , 96, 61, 99, 74] ^ SyntaxError: invalid syntax >>> answer(supplied_data, 0) Traceback (most recent call last): File "", line 1, in NameError: name 'answer' is not defined >>> answer(supplied_data, 1) Traceback (most recent call last): File "", line 1, in NameError: name 'answer' is not defined >>> answer(supplied_data, 6) Traceback (most recent call last): File "", line 1, in NameError: name 'answer' is not defined >>>
此代碼不會給出該錯誤。如果你遇到錯誤,你應該發佈完整的回溯。 (我最初表示它「工作正常」,但當然不會; for循環和if語句都毫無意義)。 –
始終發佈**完整回溯**。 –
@DanielRoseman如果'data'爲空且'n <= 1',那麼它將會生效 –