gpt4 book ai didi

python - 在 for 循环中将字符串收集到列表中

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:20 24 4
gpt4 key购买 nike

我正在读取一个文件,我在其中解析每一行中的特定字符串。在每一行中找到特定的字符串。现在我试图将这些字符串收集到一个列表中,但它不起作用。

with open('readfile.txt',"r") as data:
myList = []

for lines in data

myValues = re.findall(.......) #that's so far OK, regex finds data of interest

collect_ToList = myList.append(myValues)

print(collect_ToList )

输出:

None
None
None
None
None
None
None
None
None

调试信息:

print(type(myValues)) 

输出:

<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>

我做错了什么?

最佳答案

myList.append(item) 添加itemmyList,不需要像collect_ToList<那样将输出保存在变量中.

with open('readfile.txt',"r") as data:
myList = []
for lines in data:
myValues = re.findall(.......)
myList.append(myValues)
print(myList)

你也可以一行完成:

with open('readfile.txt',"r") as data:
myList = [re.findall(.......) for lines in data]
print(myList)

关于python - 在 for 循环中将字符串收集到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48527749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com