我们有一个名为 location 的变量。
location=[["world", 'Live'], ["alpha",'Live'], ['hello', 'Scheduled'],['alpha', 'Live'], ['just', 'Live'], ['alpha','Scheduled'], ['alpha', 'Live']]
我想找到第一个索引并计算 list["alpha",'Live'] 在位置中的出现次数。 我尝试了以下方法:
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)
返回: 索引 [1, 1, 1] 计数 [3, 3, 3]
但是有没有一种方法可以使用列表理解同时找到第一个索引,计数。
预期输出:
索引,计数 = 1, 3
最佳答案
这能解决您的问题吗?
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)
如果未找到 ['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')
由@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)
关于python - 列表:查找第一个索引并计算列表列表中特定列表的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73828396/