簡體   English   中英

從列表中的嵌套列表中找到匹配的值

[英]Find matching value in nested list from list

我讀了兩個這樣的.csv文件。

ori = "all.csv"
det = "find.csv"

names = []
namesa = []


with open(det, "r") as cursor:
    for row in cursor:
        cells = row.split(",")
        if len(cells) > 2:
            b = cells[1]
            c = b.split("-")
            names.append(c[0])


with open(ori, "r") as rcursor1: #read the document
    for trow in rcursor1: #read each row
        row1 = trow.split(",") #split it by your seperator
        namesa.append(row1)

效果很好。 namesa是一個嵌套列表,其中.csv中的每一行都是一個列表(請參見示例),而names包含我想在namesa找到的namesa 如果來自names的值在namesa ,則需要整個“嵌套列表部分”。 所以

#example
namesa = [[a,b,c,], [a1, b1, c1], [xy, cd, e2], [u1, i1, il], ...]
names = [a, u1,]
return = [[a1, b1, c1], [u1, i1, il], ...] 

#or
namesa = [[john,bill,catherina,], [marti, alex, christoph], [ben, sherlock, london], [Bern, paris, Zürich], ...]
names = [sherlock, marti]
results = [[marti, alex, christoph],  [ben, sherlock, london]]

好吧,那行不通。 那就是我到目前為止所嘗試的:

#did not return any match
d = list([b for b in namesa if b in [a for a in names]])
print d


#did not return any match neither
for a in namesa:
    for b in names:
        if b in a:
            print "match"


#well, that did not work neither
for a in namesa:
    for b in names:
        if a[5] == b:
            print "match"

沒有比賽回來。 我在excel中打開了兩個csv文件,並“手動”搜索了匹配項,這些結果返回了我的結果……我在這里做錯了什么? 使用python。

namesa = [['john', 'bill', 'catherina'], ['cat', 'dog', 'foo'], ['noodle', 'bob']]
names = ['john','foo']

嘗試這個

for n in names:
    for arr in namesa:
        if n.strip() in ''.join(arr):
            print arr

.strip因為您names列表中的值似乎有尾隨空格。

如果您使用.csv文件,建議您使用csv模塊。 我采用這種方式(假設您要查找的內容位於“姓氏”列中。如果它們位於不同的列中,則可以考慮對其進行迭代,或者name in row['surname'] or name in row['name']進行name in row['surname'] or name in row['name']取決於復雜性:

import csv
result = []
listFromCSV = []
names = ['alex','sherlock']
csvFile = open('yourFile.csv')
reader = csv.DictReader(csvFile)
fieldnames = reader.fieldnames
for row in reader:
    listFromCSV.append(row)
csvFile.close()
for name in names:
    for row in listFromCSV:
        if name.strip() in row['surname']:
            result.append(row)

如果要消除重復,請在last for循環的末尾附加break

namesa = [['john','bill','catherina',], ['marti', 'alex', 'christoph'], ['ben', 'sherlock', 'london']]

names = ['sherlock', 'marti']

for i in namesa:
  for j in names:
    if j in i:
        print i

輸出值

['marti','alex','christoph'] ['ben','sherlock','london']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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