Py学习  »  Python

在列表中运行多个参数的Python

collinsfm316 • 6 年前 • 2190 次点击  

我有一个用户ID列表 "ID" 需要他们各自的 "names" 和 "sections" 循环更新。 我给他们贴上了

ID = ["user-19533", "user-19532", "user-19531"]
names = ["test1", "test2", "test3"]
section = ["abc","pqr","xyz"]

我希望结尾/输出看起来

user-19533 would have names = test1 , section = abc
user-19532 would have names = test2 , section = pqr
user-19531 would have names = test3 , section = xyz
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54297
文章 [ 2 ]  |  最新文章 6 年前
Yonatan Karp-Rudin
Reply   •   1 楼
Yonatan Karp-Rudin    6 年前

>>> id = ["user-19533", "user-19532", "user-19531"]
>>> names = ["test1", "test2", "test3"]
>>> section = ["abc","pqr","xyz"]
>>> for i in range(len(id)):
...     print(f'{id[i]} would have name = {names[i]}, section = {section[i]}');
...

其结果是:

user-19533 would have name = test1, section = abc
user-19532 would have name = test2, section = pqr
user-19531 would have name = test3, section = xyz
Ch3steR
Reply   •   2 楼
Ch3steR    6 年前

你可以用 zip

zip()的目的是映射多个容器的类似索引,以便它们可以作为单个实体使用。

返回元组的迭代器,其中第i个元组包含每个参数序列或iterable中的第i个元素。当最短输入iterable用尽时,迭代器停止。

zip() 参考链接。

ID = ["user-19533", "user-19532", "user-19531"]
names = ["test1", "test2", "test3"]
section = ["abc","pqr","xyz"]
zipped=zip(ID,names,section)
for i,name,sec in zipped:
    print(f'{i} would have names = {name} , section = {sec}')