繁体   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