python - 如何获取for循环的第一个对象

标签 python list object for-loop

我有一个如下所示的 for 循环:

for i,x in enumerate(urunler):
    if x['fiyat'] == eklenecek['fiyat'] and x['urunobegi'] == eklenecek['urunobegi']:
        print x['id']

它输出:

1
2
3
9

如何选择此列表中的第一个对象?

最佳答案

最简单的方法是:

first_value = None
for i,x in enumerate(urunler):
    if x['fiyat'] == eklenecek['fiyat'] and x['urunobegi'] == eklenecek['urunobegi']:
        first_value = x['id']
        break

它的设置是为了如果列表中没有项目满足条件,first_value 将设置为 None

如果您想选择最后一个:

last_value = None
for i,x in enumerate(urunler):
    if x['fiyat'] == eklenecek['fiyat'] and x['urunobegi'] == eklenecek['urunobegi']:
        last_value = x['id']

但是,更好的解决方案是将其转换为列表,以便您可以随意选择任何索引。最好作为列表理解来完成:

lst = [x['id'] for x in urunler if x['fiyat'] == eklenecek['fiyat']
                       and x['urunobegi'] == eklenecek['urunobegi']]

# First element: lst[0]
# Last element: lst[-1]

关于python - 如何获取for循环的第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11899345/

相关文章:

python - Matplot : indicate with dots on the graph if conditions are met

python - 从 pandas df 中的列创建二元组

c++ - 在类对象的 vector 中找到一个值

Javascript 垃圾收集器不清除对象

c++ - Qt中的内存管理?

javascript - Django 使用 VueJS 的上下文进行渲染

python - Django 从模型或 View 调用 REST API?

python - 使用列表理解对数据帧的子集进行切片

c# - 无法使用泛型列表填充数据 GridView

Python - 实例变量列表的最小值