[英]Pass data from a csv file to a list
我想做的是設法將路線的每一行放在一個子列表中。
我制作的代碼是這樣的:
l=[]
s=f.readline()
while s!='':
for x in s:
if x not in [';',]:
l.append(x)
s=f.readline()
print(l)
代碼應該沒有導入。
我可以推薦你使用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
中獲取它們
10;10;;...
),不需要。';'
上拆分字符。'o'
顯示為左側和右側的“邊距”,因此每row
過濾掉它們row
仍然有一些東西(非空),那么 append 它到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)
Output(列表列表):
[['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']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.