我有一个有两个参数的函数。我想使用参数的不同输入来显示输出,这些参数可以使用循环在两个列表中找到。我使用一个列表(ages)成功地执行了代码,但没有使用(ages)和(game)。
# the below code works for 1 list assignment to the a argument
for a in ages:
print(age_price_event(a, 2))
# when I try this to assign the other argument I get an error.
for a in ages b in game:
print(age_price_event(a, b))文件"",游戏中年龄b中a的第1行:^ SyntaxError:无效语法
# Here is the function that I wrote
# Function that has two elements
# a is the age of person
# b is the game
def age_price_event(a, b):
str(b)
if b == 1: # looks to see if it is for 1
if a < 4: # if so execute code below
return (0)
elif a < 18:
return (10)
else:
return(15) #Stop here
if b==2: # looks to see if it is for 2
if a < 4: # if so execute code below
return (5)
elif a < 18:
return (55)
else:
return(66) #Stop Here
else: # if not game is not toady
return ("That Game is not Today")
# here are the list to be assign to the arguments
ages = [11, 22, 14, 25]
game = [ 1, 1, 2, 3]
# the below code works for 1 list assignment to the a argument
for a in ages:
print(age_price_event(a, 2))
# when I try this to assign the other argument I get an error.
for a in ages b in game:
print(age_price_event(a, b))下面的代码适用于a参数的1列表赋值
55
66
55
66当我尝试这样赋值另一个参数时,我得到了一个错误。
File "<ipython-input-158-2d5fb2f7d37f>", line 1
for a in ages b in game:
^
SyntaxError: invalid syntax发布于 2019-07-20 23:41:55
这称为并行迭代,可以按如下方式编写:
for a, b in zip(ages, games):发布于 2019-07-21 00:05:53
Python 3
for a, b in zip(ages, game):
print(age_price_event(a, b))Python 2
import itertools
for a, b in itertools.izip(ages, game):
print(age_price_event(a, b))在Python2中,itertools.izip返回迭代器而不是列表,如果有这么多元素,你想在Python2中使用itertools.izip。
https://stackoverflow.com/questions/57126183
复制相似问题