yad*_*dav 3 python list-comprehension list python-3.x
我们有一个名为 location 的变量。
location=[["world", 'Live'], ["alpha",'Live'], ['hello', 'Scheduled'],['alpha', 'Live'], ['just', 'Live'], ['alpha','Scheduled'], ['alpha', 'Live']]
Run Code Online (Sandbox Code Playgroud)
我想找到第一个索引并计算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)
Run Code Online (Sandbox Code Playgroud)
返回:索引 [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)
Run Code Online (Sandbox Code Playgroud)
如果['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')
Run Code Online (Sandbox Code Playgroud)
更清晰的代码,作者:@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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |