簡體   English   中英

將某個值在一個列表中的多個列表中的重復列表中存儲多少次

[英]Store how many times a certain value repeats in multiple lists inside of a list to a dict

我試圖在一個列表內的多個列表中獲取第一個值,並在字典/哈希中存儲多次重復的次數。

coordinates = [
        ['bg1955', '47.6740° N', '122.1215° W'],
        ['bg1955', '47.6101° N', '122.2015° W'],
        ['bg1955', '47.6062° N', '122.3321° W'],
        ['sj1955', '37.3318° N', '122.0312° W']
    ]

當我嘗試以下操作時:

my_dict = {row[0]:coordinates.count(row[0]) for row in coordinates}

my_dict的值變為:

{'sj1955': 0, 'bg1955': 0}

代替:

{'bg1955': 3}

我如何在python3中獲得以上內容? 原始數據樣本在一個列表中將有20,000多個列表,而不是上面列出的4個列表。

編輯:當我提到“ certain ,我的意思是每行中的特定位置將是row [0],而不僅僅是在字典中返回1個結果。 如果有多個不同的值重復出現,則會導致這種情況,因為我要存儲任何重復的值,可以說sw1950位於20個列表中,而jb1994位於393個列表中,則是:

{'bg1955': 3, 'sw1950': 20, 'jb1994': 393}

您可以使用defaultdict:

from collections import defaultdict

d = defaultdict(int)

coordinates = [
    ['bg1955', '47.6740° N', '122.1215° W'],
    ['bg1955', '47.6101° N', '122.2015° W'],
    ['bg1955', '47.6062° N', '122.3321° W'],
    ['sj1955', '37.3318° N', '122.0312° W']
]

for i in coordinates:
    d[i[0]] += 1

print dict(d)

輸出:

{'sj1955': 1, 'bg1955': 3}

使用計數器:

new_vals = map(list, zip(*coordinates))

print Counter(new_vals[0])

您現有的方法行不通的原因是,您正在嘗試執行以下操作:

>>> x = [[1, 1, 1]]
>>> x.count(1)

現在,您認為這將返回3因為1存在3次。 但是,這是返回的內容:

0

原因是因為這些元素在嵌套列表中,並且.count()不計算嵌套元素。

將以上內容與此對比:

>>> x = [1, 1, 1]
>>> x.count(1)
3

這是有道理的,因為那些1不在嵌套列表中。

一種解決方法是使用collections.Counter

from collections import Counter

coordinates = [
        ['bg1955', '47.6740° N', '122.1215° W'],
        ['bg1955', '47.6101° N', '122.2015° W'],
        ['bg1955', '47.6062° N', '122.3321° W'],
        ['sj1955', '37.3318° N', '122.0312° W']
    ]

count = Counter()

for coord in coordinates:
    count[coord[0]] += 1

print(count)

輸出:

Counter({'bg1955': 3, 'sj1955': 1})

現在,您可以隨意輪詢此字典以獲取您喜歡的任何項目的計數。 如果要提取重復項,可以執行以下操作:

print({ k : count[k] for k in count if count[k] > 1})

這將打印{'bg1955': 3}

使用collections.Counter

>>> from collections import Counter
>>> Counter(c[0] for c in coordinates)
Counter({'bg1955': 3, 'sj1955': 1})
>>> dict(Counter(c[0] for c in coordinates))  # If you want dictionary, not Counter
{'bg1955': 3, 'sj1955': 1}

如果只想獲取重復的鍵計數,請在創建計數器后過濾它們。

>>> counts = Counter(c[0] for c in coordinates)
>>> {key: value for key, value in counts.items() if value > 1}
{'bg1955': 3}

暫無
暫無

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

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