简体   繁体   English

如何将for循环的输出保存到Python中的列表?

[英]How to save output from for loop to a List in Python?

I have a for loop that generates strings associated with the number in the numbers list by searching through an XML file.我有一个 for 循环,它通过搜索 XML 文件生成与数字列表中的数字相关联的字符串。

tree = parse("demo.xml")
root = tree.getroot()

fields = {int(child.attrib["number"]): child.attrib["name"] for child in root}

numbers [1, 4, 5, 8, 9, 45, 78]

for number in numbers:
    print(fields.get(number, f"{number} does not exist in XML"))

so the output is like:所以输出是这样的:

Account
Name
ID
Time

I want to save this output to a list, and separate each text by a comma, so it should save this to a list that should look like:我想将此输出保存到一个列表中,并用逗号分隔每个文本,因此应将其保存到一个列表中,该列表应如下所示:

myList: [Account, Name, ID, Time] myList: [账号、姓名、ID、时间]

How can I do this?我怎样才能做到这一点?

您可以使用列表理解

myList = [fields.get(number, f"{number} does not exist in XML") for number in numbers]

Create a new empty list before starting the loop and add elements to it inside the loop body.在开始循环之前创建一个新的空列表,并在循环体内向它添加元素。

Replace代替

for number in numbers:
   print(fields.get(number, f"{number} does not exist in XML"))

with

myList = []
for number in numbers:
    myList.append(fields.get(number, f"{number} does not exist in XML")))

You can then use myList to get the output in the format you like.然后,您可以使用myList以您喜欢的格式获取输出。 From your question, it seems you may need one of these从您的问题来看,您似乎需要其中之一

print("myList:", myList)
print("myList: [", ",".join(myList), "]")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM