将相同的变量添加到元组列表中

时间:2016-03-25 21:00:51

标签: python tuples

我有以下3个列表和一个值(country [i]),我想将相同的国家/地区[i]添加到所有可用的元组中:

name = ["a", "b", "c"]
age = [1, 2, 3]
city = ["aaa", "bbb", "ccc"]
country[i]

其中country [i]等于" United States",并且我使用了以下代码:

user_info = [tuple((t,)) for t in zip(name, age, city, country[i])]

执行时我得到以下结果:

[(('a', 1, 'aaa', 'U'),), (('b', 2, 'bbb', 'n'),), (('c', 3, 'ccc', 'i'),)]

虽然我想要的是:

[('a', 1, 'aaa', 'United States'), ('b', 2, 'bbb', 'United States'), ('c', 3, 'ccc', 'United States)]

3 个答案:

答案 0 :(得分:2)

您可以将其添加到每个项目"手动":

v = (country[i], )
[t + v for t in zip(name, age, city)]

演示:

>>> country = ["United States"]
>>> i = 0
>>> name = ["a", "b", "c"]
>>> age = [1, 2, 3]
>>> city = ["aaa", "bbb", "ccc"]
>>> v = (country[i], )
>>> [t + v for t in zip(name, age, city)]
[('a', 1, 'aaa', 'United States'), ('b', 2, 'bbb', 'United States'), ('c', 3, 'ccc', 'United States')]

答案 1 :(得分:1)

result = [my_tuple + ('United States',) for my_tuple in zip(name, age, city)]

也许您有国家/地区列表,然后

result = [my_tuple + (country,) for my_tuple in zip(name, age, city) for country in countries]

答案 2 :(得分:0)

因为国家[i]只是"美国"你用for循环遍历字符串。所以你得到每一封信。国家列表需要与城市之一相同。

所以它应该是

country[i] = ["United States", "United States", "United States"]

或更容易

country[i] = ["United States"]*3
如果你只有一个

,或者你不会穿越这个国家