首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在循环中使用两个列表在一个函数中分配两个参数

在循环中使用两个列表在一个函数中分配两个参数
EN

Stack Overflow用户
提问于 2019-07-20 23:36:14
回答 2查看 161关注 0票数 0

我有一个有两个参数的函数。我想使用参数的不同输入来显示输出,这些参数可以使用循环在两个列表中找到。我使用一个列表(ages)成功地执行了代码,但没有使用(ages)和(game)。

代码语言:javascript
复制
# 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:无效语法

代码语言:javascript
复制
# 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列表赋值

代码语言:javascript
复制
55
66
55
66

当我尝试这样赋值另一个参数时,我得到了一个错误。

代码语言:javascript
复制
File "<ipython-input-158-2d5fb2f7d37f>", line 1
    for a in ages b in game:
                  ^
SyntaxError: invalid syntax
EN

回答 2

Stack Overflow用户

发布于 2019-07-20 23:41:55

这称为并行迭代,可以按如下方式编写:

代码语言:javascript
复制
for a, b in zip(ages, games):
票数 1
EN

Stack Overflow用户

发布于 2019-07-21 00:05:53

Python 3

代码语言:javascript
复制
for a, b in zip(ages, game):
    print(age_price_event(a, b))

Python 2

代码语言:javascript
复制
import itertools

for a, b in itertools.izip(ages, game):
    print(age_price_event(a, b))

在Python2中,itertools.izip返回迭代器而不是列表,如果有这么多元素,你想在Python2中使用itertools.izip

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57126183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档