[英]Count how many times a sublist is in a list
I want to know how many times a sublist is in a list next to eachother. 我想知道子列表在彼此相邻的列表中有多少次。
From another question, I received the following code to determinate if a sublist is in a list: 从另一个问题中,我收到以下代码来确定子列表是否在列表中:
list_sequence = ['Example 64', 'Example 32', 'Example 16']
my_list = ['Example 128', 'Example 64', 'Example 32', 'Example 16', 'Example 256', 'Example 512', 'Example 1024']
print(str(list_sequence)[1:-1] in str(my_list))
But I want to know, how many times the list_sequence
is NEXT to each other to determinate a combo. 但是我想知道, list_sequence
是彼此相邻的多少次来确定组合。 In the top example its 1, but if I would append list_sequence
at the start and at the very end, it still would 1. If I would add it right after Example 16 in my_list
, it would be 2. 在最上面的示例中,它是1,但是如果我在开头和list_sequence
处附加list_sequence
,它仍将是1。如果我将它添加到my_list
示例16之后,它将是2。
You can use zip
and enumerate
within a list comprehension to find the respective indices of places where your sub_list
occurs. 您可以在列表理解中使用zip
和enumerate
来查找出现sub_list
的位置的相应索引。 Then select those who's subtraction is equal to 3 (length of sub_list): 然后选择那些相减等于3(sub_list的长度)的对象:
In [6]: list_sequence = ['Example 64', 'Example 32', 'Example 16']
...:
...: my_list = ['Example 128', 'Example 64', 'Example 32', 'Example 16', 'Example 64', 'Example 32', 'Example 16', 'Example 256', 'Example 512', 'E
...: xample 1024','Example 64', 'Example 32', 'Example 16']
...:
In [7]: indices = [index for index, (i, j, k) in enumerate(zip(my_list, my_list[1:], my_list[2:])) if list_sequence == [i, j, k]]
Out[7]: [1, 4, 10]
In [8]: sum(2 * (j-i == len(list_sequence)) for i, j in zip(indices, indices[1:]))
Out[8]: 2
You an only use a generator expression within sum
to find the number of occurrences: 您只能使用sum
内的生成器表达式来查找出现次数:
In [4]: sum(list_sequence == [i, j, k] for i, j, k in zip(my_list, my_list[1:], my_list[2:]))
Out[4]: 1
But note that this will also include overlaps because zip(my_list, my_list[1:], my_list[2:]))
will give you all consequent triples. 但是请注意,这还将包括重叠,因为zip(my_list, my_list[1:], my_list[2:]))
会给您所有随后的三元组。
Count By creating dictionary of list_sequence 通过创建list_sequence字典进行计数
list_sequence = ['Example 64', 'Example 32', 'Example 16']
my_list = ['Example 128', 'Example 64', 'Example 32', 'Example 16','Example 16', 'Example 256', 'Example 512', 'Example 1024']
dic=dict()
for i in list_sequence :
for j in my_list :
if i==j:
dic[i]=dic.get(i,0)+1
print(dic)
{'Example 64': 1, 'Example 32': 1, 'Example 16': 2} {“示例64”:1,“示例32”:1,“示例16”:2}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.