【发布时间】:2021-05-08 03:44:48
【问题描述】:
我想做的是设法将路线的每一行放在一个子列表中。
我做的代码是这个:
l=[]
s=f.readline()
while s!='':
for x in s:
if x not in [';',]:
l.append(x)
s=f.readline()
print(l)
代码应该没有导入。
【问题讨论】:
我想做的是设法将路线的每一行放在一个子列表中。
我做的代码是这个:
l=[]
s=f.readline()
while s!='':
for x in s:
if x not in [';',]:
l.append(x)
s=f.readline()
print(l)
代码应该没有导入。
【问题讨论】:
10;10;;...),不需要。';' 字符上拆分。'o's 显示为左侧和右侧的“边距”,因此请根据 row 过滤掉它们
row 仍有内容(非空),则将其附加到lines。
o 的开始行和结束行lines = []
with open(csvfile) as f:
f.readline() # skip the first line, not needed
for line in f:
if line.endswith('\n'): # in case the last line doesn't end in a newline
line = line[:-1]
# create a row which ignores the 'o's
row = [c for c in line.split(';') if c != 'o']
if row: # skip empty rows (all 'o's)
lines.append(row)
print(lines)
输出(列表列表):
[['x', 'x', 'x', 'x', 'x', 'x', 'x', '', '', ''],
['x', '', '', '', '', '', 'x', '', '', ''],
['x', 'x', '', '', '', '', 'x', 'x', 'x', ''],
['', 'x', 'x', '', '', '', '', '', 'x', 'x'],
['', '', 'x', '', '', '', '', '', '', 'x'],
['x', 'x', 'x', '', '', '', '', '', '', 'x'],
['x', '', '', '', '', '', '', '', '', 'x'],
['x', 'x', 'x', 'x', 'x', 'x', '', '', '', 'x'],
['', '', '', '', '', 'x', '', '', '', 'x'],
['', '', '', '', '', 'x', 'x', 'x', 'x', 'x']
]
如果您确实真的想要所有 o 出现在任何地方,那么请删除一些 if 条件:
lines = []
with open(csvfile) as f:
f.readline() # skip the first line
for line in f:
if line.endswith('\n'): # in case the last line doesn't end in a newline
line = line[:-1]
row = [c for c in line.split(';')]
lines.append(row)
print(lines)
# output:
[['o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o'],
['o', 'x', 'x', 'x', 'x', 'x', 'x', 'x', '', '', '', 'o'],
['o', 'x', '', '', '', '', '', 'x', '', '', '', 'o'],
['o', 'x', 'x', '', '', '', '', 'x', 'x', 'x', '', 'o'],
['o', '', 'x', 'x', '', '', '', '', '', 'x', 'x', 'o'],
['o', '', '', 'x', '', '', '', '', '', '', 'x', 'o'],
['o', 'x', 'x', 'x', '', '', '', '', '', '', 'x', 'o'],
['o', 'x', '', '', '', '', '', '', '', '', 'x', 'o'],
['o', 'x', 'x', 'x', 'x', 'x', 'x', '', '', '', 'x', 'o'],
['o', '', '', '', '', '', 'x', '', '', '', 'x', 'o'],
['o', '', '', '', '', '', 'x', 'x', 'x', 'x', 'x', 'o'],
['o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o']]
【讨论】:
endswith() 是 Python 内置的字符串。但是,如果您不想使用它,请执行if line[-1] == '\n'):,因为它只检查行的最后一个字符。
line = line[:-1] if line[-1] == '\n' else line
我可以推荐你使用csv 模块
import csv
with open('blah.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
rows=list(csv_reader)
path=rows[1:]
print(path)
我不确定你想对前两个值做什么。
但是你可以很容易地从rows得到它们
【讨论】:
rows = [row.split(';') for row in open('blah.csv').readlines()]。
for row in rows: row[len(row)-1] = row[len(row)-1].rstrip()