【问题标题】:Searching lists then calling same place from other lists [closed]搜索列表然后从其他列表中调用同一个地方[关闭]
【发布时间】:2016-04-03 08:18:41
【问题描述】:

我希望我的程序搜索 resident 并且如果它是一个特定的值,它将打印来自其他列表的相同放置的数据。例如,在这种情况下,我希望它打印出来;

“名字叫艾伦,7岁,他们不住在原地”,

还有,

“名字叫玛格丽特,66岁,他们不住在原地”

name = ["Alan", "Susan", "Margaret"]
age = [7, 34, 66]
resident = [0, 1, 0]

if resident = 0:
    print ("name is {}, age is {} and they do not live in place".format(name[], age[]))

【问题讨论】:

标签: python


【解决方案1】:
for person, ages, residency in zip(name,age,resident):
    if residency == 0:
        print("name is {0}, age is {1} and they do not live in place".format(person, ages))

zip 接受多个列表并返回一个元组列表。这是一个例子:

zip(name, age, resident)
>>>> [('Alan', 7, 0), ('Susan', 34, 1), ('Margaret', 66, 0)]

遍历每个元组非常容易。

【讨论】:

    【解决方案2】:

    考虑使用enumerate,它将提供迭代列表中的索引和项目:

    >>> for i,x in enumerate(resident):
            if x == 0:
                print("name is {0}, age is {1} and they do not live in place".format(name[i], age[i]))
    
    
    name is Alan, age is 7 and they do not live in place
    name is Margaret, age is 66 and they do not live in place
    

    【讨论】:

      【解决方案3】:

      可以使用常用的%s字符串替换:

      name = ["Alan", "Susan", "Margaret"]
      age = [7, 34, 66]
      resident = [0, 1, 0]
      
      if resident[0] == 0:print ("name is %s, age is %s and they do not live in place"%(name[0],age[0]))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        相关资源
        最近更新 更多