python列表的问题

发布于 2024-10-25 00:36:51 字数 318 浏览 5 评论 0原文

您好,我正在尝试创建一个列表,通过 for 循环从 txt 文件中逐行读取添加到该列表中。我在列表中收到语法错误,但不确定如何解决该问题???

import re
file = open("text.txt","r")
text = file.readlines()
file.close()

line_count=0

for line in text:
    User_Input_list[] += [] + line.split()
    line_count += 1

问题似乎出在列表声明的倒数第二行

Hi im trying to create a list adding to it via a for loop reading line by line from a txt file. Im getting a syntax error on the list but am unsure about how to fix the problem ???

import re
file = open("text.txt","r")
text = file.readlines()
file.close()

line_count=0

for line in text:
    User_Input_list[] += [] + line.split()
    line_count += 1

the problem seems to be on the second last line with the declaration of the list

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

恏ㄋ傷疤忘ㄋ疼 2024-11-01 00:36:51

这样做:

input = []
line_count = 0
with open("text.txt","r") as file:
    for line in file:
        input.extend(line.split())
        line_count += 1

Do it like this:

input = []
line_count = 0
with open("text.txt","r") as file:
    for line in file:
        input.extend(line.split())
        line_count += 1
Oo萌小芽oO 2024-11-01 00:36:51

为什么不呢
UserInputList += line.split()

Why not
UserInputList += line.split()?

时光清浅 2024-11-01 00:36:51

如果您希望文件中的每一行成为列表中的单独元素,可以使用以下更简单的方法:

import re
file = open("text.txt","r")
text = file.readlines()
file.close()

line_count=0
line_list = []
for line in text:
    line_list.append(line)
    line_count += 1

或使用列表理解:

import re
file = open("text.txt","r")
text = file.readlines()
file.close()

line_list = []
[line_list.append(a_line) for a_line in text]
line_count = len(line_list)

If you want each line in the file to be a separate element in the list, here's a simpler way to do it:

import re
file = open("text.txt","r")
text = file.readlines()
file.close()

line_count=0
line_list = []
for line in text:
    line_list.append(line)
    line_count += 1

Or using list comprehension:

import re
file = open("text.txt","r")
text = file.readlines()
file.close()

line_list = []
[line_list.append(a_line) for a_line in text]
line_count = len(line_list)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文