Python:列表问题
我已经读取了一个文本文件,并把每一行转换成了一个列表。
使用这个脚本:
l = [s.strip().split() for s in open("cluster2.wcnf").readlines()]
我该如何做:
- 打开的文件是动态的,而不是静态的?也就是说,用户可以选择要打开的文件。
- 在转换成列表后,选择特定的行来读取。
- 将对象分配给列表中的值。
- 选择每一行中的第一个、最后一个或多个值?
提前谢谢你
5 个回答
0
这是一种更优化的方式来读取整个文件,并且每一行也会被分割成一个列表。
import csv, sys
# 1 - User specifies file
file = input('File: ')
f = open(file, 'r')
reader = csv.reader(f, delimiter=' ')
lines = list(reader)
f.close()
# 2 - Select specific lines
print lines[4]
# 3 - Assign to list
lines[4] = obj # makes the whole line into that obj
lines[4][0] = obj # replaces the first item on the line with that obj
# 4 - Select first, last or a number of values
print lines[4][0] # first item in line 4
print lines[4][-1] # last item in line 4
print lines[4][1:4] # 2nd, 3rd and 4th items in line 4
0
像是用用户输入的名字打开文件(也就是用字符串)和在列表中选择或分配项目,这些都是非常基础的Python概念。我觉得你最好的办法就是读一本好的Python书。我推荐你看看Dive Into Python这本书。
1
首先,你需要把 .readlines()
从你的列表推导式中去掉。
其次,l
是一个包含多个列表的列表,要访问第一行的话,只需要用 l[0]
。而第一行的第一个元素就是 l[0][0]
。
不过,我觉得用这种方法解决不断增长的文件问题是行不通的。如果你说的动态是指文件名,而不是文件的行为,那么你可以把写死的文件名换成一个变量,这个变量的值可以通过用户输入来定义。