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“值。第二个列表应该包含所有的“新案例”值。
我的列表列在
0 188714
1 285878
2 1044839
3 812112
4 662511
5 834945
6 869684
7 397661
8 484949我需要这样
x = [ 0, 1 , 2, 3,...]
y = [188714, 285878, 1044839, 812112, ...]我尝试了很多不同的东西,我对Python很陌生,并试图弄清楚如何启动它。有人能把我引向正确的方向吗?
发布于 2022-04-19 22:33:52
假设您的数据文件在一行中包含了所有这些数字,那么应该可以这样做:
# 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)后续行动
鉴于这些数据:
0 188714
1 285878
2 1044839
3 812112
4 662511
5 834945
6 869684
7 397661
8 48494我的代码产生了这样的结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[188714, 285878, 1044839, 812112, 662511, 834945, 869684, 397661, 48494]这正是你说的你想要的。
发布于 2022-04-19 23:04:10
with open('covid.txt','rt') as f:
all_lines = [line.split(' ') for line in f]
x, y = zip(*all_lines)不过,x和y将是元组。您可以使用list(x)进行转换
https://stackoverflow.com/questions/71931996
复制相似问题