簡體   English   中英

如何計算嵌套元組列表中字符串的出現次數?

[英]How to count occurrences of a string in nested tuple list?

我在 python 中有一個嵌套的元組列表:

myList = [(12345, "John Doe"), (345678, 'Marie Doe'), (434566, 'Marie Doe'), (665533, 'Marie Doe'), (23456, 'John Doe'), (657332211, 'Amanda Doe')]

並嘗試將名稱的出現作為兩個單獨的列表:

occurrences = [2, 3, 1]
names = ['John Doe', 'Marie Doe', 'Amanda Doe']

到目前為止,這個給了我嵌套元組中的項目總數,但不確定如何生成上述內容:

Total = len(myList)

有人可以幫我解決這個問題嗎? 先感謝您!

您可以做的是創建一個dict ,其中鍵是名稱,值是它們在myList中的計數。

 myList = [(12345, "John Doe"), (345678, 'Marie Doe'), (434566, 'Marie Doe'), (665533, 'Marie Doe'), (23456, 'John Doe'), (657332211, 'Amanda Doe')]

# Initializing a dict with key: name and value: 0.
dict_name_count = {name: 0 for _, name in myList}

# Iterating over tuples in `myList`, picking name (the second entry in tuple) ignoring the number.
for _, name in myList:
    dict_name_count[name] += 1

print(dict_name_count)
# Results in: {'John Doe': 2, 'Marie Doe': 3, 'Amanda Doe': 1}

# To get separate lists:
names = list(dict_name_count.keys())
occurrences = list(dict_name_count.values())

這是我將使用熊貓做的事情:

import pandas as pd

df = pd.DataFrame(myList).groupby(1, as_index=False).count()

occurrences = df[0].to_list()
names = df[1].to_list()

輸出:

names : ['Amanda Doe', 'Joe Doe', 'John Doe', 'Marie Doe']
occurrences : [1, 1, 1, 3]

您可以將名稱解壓縮到一個列表中,然后運行該列表的計數:

all_names = [elem[1] for elem in myList]
names = []
occurrencs = []
for name in set(all_names):
    names.append(name)
    occurrences.append(all_names.count(name))

嘗試這個

    myList = [(12345, "John Doe"),
          (345678, 'Marie Doe'),
          (434566, 'Marie Doe'),
          (665533, 'Marie Doe'),
          (23456, 'John Doe'),
          (657332211, 'Amanda Doe')
          ]
namelist=[name[1] for name in myList]
names=[]
for name in namelist:
    if name not in names:
        names.append(name)

occurrences=[namelist.count(name) for name in names]
print(occurrences)
print(names)

暫無
暫無

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

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