在 Python 中使用 zip() 从列表中获取一个元组
Get a tuple from lists with zip() in Python
我被困在这段代码中,我必须通过使用 zip 函数和 for 循环(没有索引或枚举(强制))从三个列表中获取一个元组。我需要得到这个:
answer = (
("John", "London", "Cloudy"),
("Bruno", "San Paulo", "Sunny"),
("Mike", "Sevilla", "Windy"),
)
我试过这个(在一个函数内):
answer = []
for item in zip([name], [place], [weather]):
answer.append(item)
answer = tuple(answer)
return answer
事实是,我得到了这个输出:
((["John", "Bruno", "Mike"], ["London", "San Paulo", "Sevilla"], ["Cloudy", "Sunny", "Windy"]),)
所以,不仅里面的括号有问题,顺序也有问题。有人可以给个提示吗?谢谢。
不要在变量周围放置 []
。现在您正在压缩这些列表,而不是变量的内容。
只需使用:
answer = tuple(zip(name, place, weather))
你可以这样做:
tuple(zip(name, place, weather))
(('john', 'london', 'cloudy'), ('bruno', 'san paulo', 'sunny'), ('mike', 'sevilla', 'windy'))
我被困在这段代码中,我必须通过使用 zip 函数和 for 循环(没有索引或枚举(强制))从三个列表中获取一个元组。我需要得到这个:
answer = (
("John", "London", "Cloudy"),
("Bruno", "San Paulo", "Sunny"),
("Mike", "Sevilla", "Windy"),
)
我试过这个(在一个函数内):
answer = []
for item in zip([name], [place], [weather]):
answer.append(item)
answer = tuple(answer)
return answer
事实是,我得到了这个输出:
((["John", "Bruno", "Mike"], ["London", "San Paulo", "Sevilla"], ["Cloudy", "Sunny", "Windy"]),)
所以,不仅里面的括号有问题,顺序也有问题。有人可以给个提示吗?谢谢。
不要在变量周围放置 []
。现在您正在压缩这些列表,而不是变量的内容。
只需使用:
answer = tuple(zip(name, place, weather))
你可以这样做:
tuple(zip(name, place, weather))
(('john', 'london', 'cloudy'), ('bruno', 'san paulo', 'sunny'), ('mike', 'sevilla', 'windy'))