我有一個 csv 檔案,其中有一行需要放入串列中。該行的一個示例是
row A
apple
apple
apple
orange
orange
watermelon
我需要將該行讀入一個沒有重復名稱的串列,所以它看起來像
['apple','orange','watermelon']
這是我當前針對此問題的代碼:
import csv
start = open('fruits.csv', 'r')
reader = csv.reader(start)
next(reader, None)
for row in reader:
fruits = [row[1]]
print(fruits)
我當前的代碼只是將每一行放入自己的串列中。
uj5u.com熱心網友回復:
在您提供的代碼中,每次回圈通過 for 回圈時,您都會創建一個包含單個專案的新串列。相反,您希望維護一個不斷增長的串列
import csv
start = open('data.txt', 'r')
reader = csv.reader(start)
next(reader, None)
fruits = [] #define an empty list
for row in reader:
fruits.append(row[1]) #add to the list
請注意,在您提供的資料示例中,只有一列,因此如果我們嚴格使用該示例row[0],則應該使用該列row[1]
要使串列唯一,您可以將其轉換為強制唯一性的集合:
fruits = set(fruits)
如果您希望將其轉換回串列,請嘗試以下操作:
fruits = list(fruits)
請注意,此方法不保證串列的順序保持不變。
uj5u.com熱心網友回復:
import csv
data = 'fruits.csv'
fruits = []
# read csv, append unique items to list
with open(data, 'r') as f:
reader = csv.reader(f)
for row in reader:
if row[0] not in fruits:
fruits.append(row[0])
# output: ['row A', 'apple', 'orange', 'watermelon']
print(fruits_in)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451320.html
標籤:Python python-3.x 列表 CSV
