使用charachter列表列出元组列表

时间:2017-07-03 17:40:20

标签: python

我以这种形式列出了一个名单:

name = ['John','Jack','Benny', 'Jane']

location = [(219, 459, 374, 304)]

当我做

for (top, right, bottom, left), name in list(zip(location, name)):
    print(location, name)

我得到以下结果:

[(219, 459, 374, 304)] J

但我想得到这个结果:

[(219, 459, 374, 304)] John

此外,现在假设我的列表如下:

name = ['John','Jack', 'Jane']

location = [(219, 459, 374, 304), (200, 459, 350, 214), (159, 349, 264, 104)]

如何以这种形式获得上述for循环的结果:

[(219, 459, 374, 304)] John
[(200, 459, 350, 214)] Jack
[(159, 349, 264, 104)] Jane

3 个答案:

答案 0 :(得分:4)

你得到的原因

[(219, 459, 374, 304)] J

而不是:

[(219, 459, 374, 304)] John

是因为您重复使用了name变量:

for (top, right, bottom, left), name in list(zip(location, name)):
    print(location, name)

因此,当您第二次运行时,name指的是您第一次尝试的最后name,大概是'Jane'。所以第一个元素是'J',因为它迭代字符串

小心你的变量名。并发布可重现的示例。如果您尝试按照建议的新流程执行此操作,则您可能没有看到此行为。

答案 1 :(得分:2)

试试这个:

from itertools import izip_longest

name = ['John','Jack', 'Jane']

location = [(219, 459, 374, 304), (200, 459, 350, 214), (159, 349, 264, 104)]

new = [i for i in izip_longest(location, name) if None not in i]

izip_longest非常有用,因为它可以过滤掉两个长度不匹配的列表或元组的任何场合:

name = ['John','Jack','Benny', 'Jane']

location = [(219, 459, 374, 304)]

new = [i for i in izip_longest(location, name) if None not in i]

print new

输出:

[((219, 459, 374, 304), 'John')]

答案 2 :(得分:1)

我刚刚复制并粘贴了您的示例代码

>>> name = ['John','Jack', 'Jane']
>>> location = [(219, 459, 374, 304), (200, 459, 350, 214), (159, 349, 264, 104)]
>>> for n,loc in zip(name,location):
...    print("%s %s"%(n,loc))
...
John (219, 459, 374, 304)
Jack (200, 459, 350, 214)
Jane (159, 349, 264, 104)