我有一个字符串:
seq = '01234567890123456789'
我想首先分成4个区间。我找到了之前的答案
n = 4
[seq[i:i+n] for i in range(0,len(seq,n)]
给了我
['0123', '4567', '8901', '2345', '6789']
现在我想将我的chunked up字符串与子字符串列表中的每个条目进行比较:
mylist = ['0123', '1111' '2345']
并返回一个数组,该数组计算每个子字符串在原始字符串中出现的次数。我看到很多在较大的字符串中找到一个子字符串的例子,但我对如何用一个子字符串列表这样做感到困惑
答案 0 :(得分:0)
generated = ['0123', '4567', '8901', '2345', '6789']
mylist = ['0123', '1111' '2345']
result = [generated.count(element) for element in mylist ]
list.count(e)
会返回e
中list
的出现次数,因此我们可以为mylist
中的每个项目执行此次。
在这种情况下,结果为[1,0,1]
,这意味着'0123'
出现generated
一次,'1111'
未显示,'2345'
也出现过一次。
无法从您的描述中找出您想要比较事件的方式。如果我以错误的方式说出来并且我很乐意编辑。
答案 1 :(得分:0)
chunked = ['0123', '4567', '8901', '2345', '6789']
mylist = ['0123', '1111', '2345']
my_count = {}
for m in mylist:
for c in chunked:
if m == c:
try:
my_count[m] += 1
except KeyError:
my_count[m] = 1
>>> chunked
['0123', '4567', '8901', '2345', '6789']
>>> mylist
['0123', '1111', '2345']
>>> my_count
{'2345': 1, '0123': 1}
>>>
答案 2 :(得分:0)
seq = '01234567890123456789'
chunks = ['0123', '4567', '8901', '2345', '6789']
dict = {}
for elt in chunks:
dict[elt] = seq.count(elt)
print(dict)
答案 3 :(得分:0)
在列表中添加包含块及其计数的元组,在本例中称为计数。
In [37]: seq = '01234567890123456789'
In [38]: chunks = ['0123', '4567', '8901', '2345', '6789']
In [39]: mylist = ['0123', '1111' '2345']
In [40]: counts = [(i, mylist.count(i)) for i in chunks]
In [41]: counts
Out[41]: [('0123', 1), ('4567', 0), ('8901', 0), ('2345', 0), ('6789', 0)]