Adding The Same Variable To A List Of Tuples
I've the below 3 lists and a value (country[i]) and i want to add the same country[i] to all tuples available: name = ['a', 'b', 'c'] age = [1, 2, 3] city = ['aaa', 'bbb', 'ccc'] c
Solution 1:
You can add it to each of the item "manually":
v = (country[i], )
[t + v for t in zip(name, age, city)]
Demo:
>>> country = ["United States"]
>>> i = 0>>> name = ["a", "b", "c"]
>>> age = [1, 2, 3]
>>> city = ["aaa", "bbb", "ccc"]
>>> v = (country[i], )
>>> [t + v for t inzip(name, age, city)]
[('a', 1, 'aaa', 'United States'), ('b', 2, 'bbb', 'United States'), ('c', 3, 'ccc', 'United States')]
Solution 2:
result = [my_tuple + ('United States',) for my_tuple in zip(name, age, city)]
Maybe you have list of countries, then
result = [my_tuple + (country,) for my_tuple in zip(name, age, city) for country in countries]
Solution 3:
since country[i] is just "United States" you step through the string with the for loop. So you get each single letter. The list of countries need to be same long as the one of cities.
So it should be
country[i] = ["United States", "United States", "United States"]
or easier
country[i] = ["United States"]*3
or you dont step through the country if you have just one
Post a Comment for "Adding The Same Variable To A List Of Tuples"