[英]How to count elements in a list of lists of strings
If a have a list like this: 如果有这样的列表:
[['welcome','a1'],['welcome','a1'],['hello','a2'],['hello','a3']]
and I want to return something like this: 我想返回这样的内容:
[['welcome','a1', 2],['hello','a2', 1],['hello','a3', 1]]
If the same pair of strings in a sublist is encountered, increment the count 如果在子列表中遇到相同的字符串对,请增加计数
What I have so far: 到目前为止,我有:
counter = 0
for i in mylist:
counter += 1
if i[0]== i[0]:
if i[1] == i[1]:
counter -= 1
ouptut.append([mylist, counter])
I'm new at this and I appreciate your help! 我是新手,感谢您的帮助!
Use a set
here to get only unique items: 在此处使用一
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]]
Explanation: 说明:
Set always returns unique items from an iterable or iterator, but as sets can only contain immutable item so you should convert them to a tuple first. 集合总是从迭代器或迭代器返回唯一项,但是集合只能包含不可变项,因此您应该首先将它们转换为元组。 A verbose version of the above code, only difference is that will also preserve the original or
上面代码的详细版本,唯一的不同是还将保留原始或
>>> 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')])
Now use a list comprehension to get the expected output: 现在使用列表推导来获得预期的输出:
>>> [list(item) + [1] for item in s]
[['welcome', 'a1', 1], ['hello', 'a3', 1], ['hello', 'a2', 1]]
If the order of items matter( sets
don't preserve order), then use this: 如果项目的顺序很重要(
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]]
I am not sure what's the point of using 1
here. 我不确定在这里使用
1
什么意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.