簡體   English   中英

將數據從 csv 文件傳遞到列表

[英]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中獲取它們

  1. 跳過第一行( 10;10;;... ),不需要。
  2. 閱讀每一行並在';'上拆分字符。
  3. 'o'顯示為左側和右側的“邊距”,因此每row過濾掉它們
  4. 如果該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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM