![](/img/trans.png)
[英]Taking a column from a csv file and putting it into a list in python
[英]Putting column values from text file into a list in python
我有一個這樣的文本文件:
a w b x c,d y e,f z
我想將第一列的值放入一個沒有重復的列表中。 現在我從第一列獲取值,我這樣做是這樣的:
f=open("file.txt","r")
lines=f.readlines()
firstCol=[]
for x in lines:
firstCol.append(x.split(' ')[0])
f.close()
在下一步中,我想像以前一樣用逗號分隔符分隔值,但隨后我得到一個 output ,如下所示:
[['a'], ['b'], ['c', 'd'], ['e', 'f']]
如何將其轉換為一維事物以便之后能夠刪除重復項? 我是 python 的初學者。
您可以使用itertools.chain
來展平您的列表列表,然后您可以使用內置的 class set
來刪除重復項:
from itertools import chain
l = [['a'], ['b'], ['c', 'd'], ['e', 'f']]
set(chain.from_iterable(l))
# {'a', 'b', 'c', 'd', 'e', 'f'}
要展平您的列表,您還可以使用列表理解:
my_l = [e for i in l for e in i]
# ['a', 'b', 'c', 'd', 'e', 'f']
與 2 個簡單for
循環相同:
my_l = []
for i in l:
for e in i:
my_l.append(e)
您可以在第一次拆分后立即拆分它,並且必須使用 extend 而不是 append。
f=open("file.txt","r")
lines=f.readlines()
firstCol=[]
for x in lines:
firstCol.extend(x.split(' ')[0].split(','))
f.close()
print(firstCol)
結果
['a', 'b', 'c', 'd', 'e', 'f']
或者如果你想保留 firstCol
f=open("file.txt","r")
lines=f.readlines()
firstCol=[]
for x in lines:
firstCol.append(x.split(' ')[0])
f.close()
one_dimension = []
for col in firstCol:
one_dimension.extend(col.split(','))
print(firstCol)
print(one_dimension)
結果
['a', 'b', 'c,d', 'e,f']
['a', 'b', 'c', 'd', 'e', 'f']
如果您的代碼很好,您可以保持這樣並從執行以下操作的列表列表中刪除重復項:
import itertools
firstCol.sort()
firstCol = list(x for x,_ in itertools.groupby(firstCol))
如果要將列表列表轉換為一個項目列表:
firstCol = [x for y in firstCol for x in y]
如果您還想刪除重復項:
firstCol = list(set([x for y in firstCol for x in y]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.