【问题标题】:List: Find the first index and count the occurrence of a specific list in list of lists列表:查找第一个索引并计算列表列表中特定列表的出现次数
【发布时间】:2022-09-23 21:31:25
【问题描述】:

我们有一个名为 location 的变量。

location=[[\"world\", \'Live\'], [\"alpha\",\'Live\'], [\'hello\', \'Scheduled\'],[\'alpha\', \'Live\'], [\'just\', \'Live\'], [\'alpha\',\'Scheduled\'], [\'alpha\', \'Live\']]

我想找到第一个索引并计算出现列表[\"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

  • 您是否查看过 .count().index() 列表方法?
  • 预期的输出是什么样的?
  • 你的意思是index, count = location.index([\'alpha\', \'Live\']), location.count([\'alpha\', \'Live\']) 吗?
  • @AndrejKesely 正要写这个,你应该添加一个答案。

标签: python python-3.x list list-comprehension


【解决方案1】:

这能解决你的问题吗?

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)

【讨论】:

  • 我想我只是想对列表理解感兴趣。谢谢!
  • 花哨没有错 :),请务必标记正确的答案以供将来参考。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-15
  • 1970-01-01
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
相关资源
最近更新 更多