[英]List: Find the first index and count the occurrence of a specific list in list of lists
we have a variable named location.我们有一个名为 location 的变量。
location=[["world", 'Live'], ["alpha",'Live'], ['hello', 'Scheduled'],['alpha', 'Live'], ['just', 'Live'], ['alpha','Scheduled'], ['alpha', 'Live']]
i want to find the first index and count occurrence of list["alpha",'Live'] in location.我想在位置找到第一个索引并计算list["alpha",'Live']的出现次数。 i tried the following:
我尝试了以下方法:
index= [location.index(i) for i in location if i ==["alpha", 'Live'] ]
count = [location.count(i) for i in location if i ==["alpha",'Live'] ]
print('index',index)
print('count', count)
this returns: index [1, 1, 1] count [3, 3, 3]这将返回: index [1, 1, 1] count [3, 3, 3]
but is there a way to find both first index, count simultaneously using list comprehension.但是有没有办法找到第一个索引,使用列表理解同时计数。
expected output:预期 output:
index, count = 1, 3索引,计数 = 1, 3
does this solve you problem?这能解决你的问题吗?
location=[["world", 'Live'], ["alpha",'Live'], ['hello', 'Scheduled'],['alpha', 'Live'], ['just', 'Live'], ['alpha','Scheduled'], ['alpha', 'Live']]
index= location.index(["alpha",'Live'])
count = location.count(["alpha",'Live'])
print('index',index)
print('count', count)
if ['alpha','live']
is not found, find the first ['alpha',??]
and print its index and count.如果未找到
['alpha','live']
,则找到第一个['alpha',??]
并打印其索引和计数。
location = [["world", 'Live'], ["alpha", 'Live'], ['hello', 'Scheduled'], [
'alpha', 'Live'], ['just', 'Live'], ['alpha', 'Scheduled'], ['alpha', 'Live']]
key = ["alpha", 'Lsive']
count = location.count(key)
if count:
index = location.index(key)
print('count', count)
print('index', index)
else:
for i in location:
if i[0] == key[0]:
key = i
count = location.count(key)
index = location.index(key)
print('count', count)
print('index', index)
else:
print('not found')
cleaner code by @yadavender yadav @yadavender yadav 编写的更简洁的代码
location = [["alpha", 'Scheduled'], ["alpha", 'Live'], ['hello', 'Scheduled'], [
'alpha', 'Live'], ['just', 'Live'], ['alpha', 'Scheduled'], ['alpha', 'Live']]
key = ["alpha", 'Scheduled']
count = location.count(key)
if count:
index = location.index(key)
else:
index=[location.index(i) for i in location if i[0]=="alpha"][0]
print('count', count)
print('index', index)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.