首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打开txt文件并从txt文件创建列表。

打开txt文件并从txt文件创建列表。
EN

Stack Overflow用户
提问于 2022-04-19 22:24:45
回答 2查看 68关注 0票数 0
代码语言:javascript
复制
file = open('covid.txt', 'rt')
everything = file.read()
list = file.read()
i = [row.rstrip('\n') for row in everything]
print(i)
    covid = []
    counter = 0
    for number in line.split(" "):
        file.append(number)
    for x in range(4):
        print(x)

file.close()

我试图将"covid.txt“文件读入两个列表中。第一个列表应该包含文件中的所有"day“值。第二个列表应该包含所有的“新案例”值。

我的列表列在

代码语言:javascript
复制
0 188714 
1 285878
2 1044839
3 812112
4 662511
5 834945
6 869684
7 397661
8 484949

我需要这样

代码语言:javascript
复制
x = [ 0, 1 , 2, 3,...]
y = [188714, 285878, 1044839, 812112, ...]

我尝试了很多不同的东西,我对Python很陌生,并试图弄清楚如何启动它。有人能把我引向正确的方向吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-04-19 22:33:52

假设您的数据文件在一行中包含了所有这些数字,那么应该可以这样做:

代码语言:javascript
复制
# Read the words from the file.  This is a list, one word per entry.
words = open('covid.txt','rt').read().split()
# Convert them to integers.
words = [int(i) for i in words]
# Divide into two lists by taking every other number.
x = words[0::2]
y = words[1::2]
print(x)
print(y)

后续行动

鉴于这些数据:

代码语言:javascript
复制
0 188714
1 285878
2 1044839
3 812112
4 662511
5 834945
6 869684
7 397661
8 48494

我的代码产生了这样的结果:

代码语言:javascript
复制
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[188714, 285878, 1044839, 812112, 662511, 834945, 869684, 397661, 48494]

这正是你说的你想要的。

票数 0
EN

Stack Overflow用户

发布于 2022-04-19 23:04:10

代码语言:javascript
复制
with open('covid.txt','rt') as f:
    all_lines = [line.split(' ') for line in f]
x, y = zip(*all_lines)

不过,xy将是元组。您可以使用list(x)进行转换

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71931996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档