簡體   English   中英

如何計算字符串列表中的元素

[英]How to count elements in a list of lists of strings

如果有這樣的列表:

[['welcome','a1'],['welcome','a1'],['hello','a2'],['hello','a3']]

我想返回這樣的內容:

[['welcome','a1', 2],['hello','a2', 1],['hello','a3', 1]]

如果在子列表中遇到相同的字符串對,請增加計數

到目前為止,我有:

counter = 0
for i in mylist:
  counter += 1 
  if i[0]== i[0]:
    if i[1] == i[1]:
        counter -= 1
 ouptut.append([mylist, counter])

我是新手,感謝您的幫助!

在此處使用一set僅獲取唯一項:

>>> lis = [['welcome','a1'],['welcome','a1'],['hello','a2'],['hello','a3']] 
>>> [list(x) + [1] for x in set(map(tuple, lis))]
>>> [['welcome', 'a1', 1], ['hello', 'a3', 1], ['hello', 'a2', 1]]

說明:

集合總是從迭代器或迭代器返回唯一項,但是集合只能包含不可變項,因此您應該首先將它們轉換為元組。 上面代碼的詳細版本,唯一的不同是還將保留原始或

>>> lis = [['welcome','a1'],['welcome','a1'],['hello','a2'],['hello','a3']] 
>>> s = set()
>>> for item in lis:
...     tup = tuple(item)  #covert to tuple
...     s.add(tup)
>>> s
set([('welcome', 'a1'), ('hello', 'a3'), ('hello', 'a2')])

現在使用列表推導來獲得預期的輸出:

>>> [list(item) + [1] for item in s]
[['welcome', 'a1', 1], ['hello', 'a3', 1], ['hello', 'a2', 1]]

如果項目的順序很重要( sets不保留順序),請使用以下命令:

>>> seen = set()
>>> ans = []
>>> for item in lis:
...     tup = tuple(item)
...     if tup not in seen:
...         ans.append(item + [1])
...         seen.add(tup)
...         
>>> ans
[['welcome', 'a1', 1], ['hello', 'a2', 1], ['hello', 'a3', 1]]

我不確定在這里使用1什么意義。

暫無
暫無

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

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