python - 列表:查找第一个索引并计算列表列表中特定列表的出现次数

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

我们有一个名为 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/

相关文章:

python - 带日期的 matplotlib 固定定位器

php - 使用 PHP/Python 下载 url 中的特定文件

python - 当 x 值之间发生单击时,在固定 x 值上绘制 h 线

python - 在桌面壁纸 Ubuntu 上转换 TensorFlow 对象检测的输出

Python 3 - 在当前按字母顺序排列的文档中查找插入字符串的位置

python - GAE 属性错误

python - 在 Python 中解析包含 "\u as UTF-8 bytes"的 JSON

django - 在 django、csrf_token 上测试 post 请求

python - 如何按其元素的值对列表进行排序,该值在 Python 中的不同列表中定义

php - 使用递归函数在列表中将 SQL 帖子相互分组