python - 在 Python 中搜索列表中的元素

标签 python python-2.7

我有以下列表

b = [[1,2], [1,3], [2,4], [2,5], [3,4], [3,5], [4,6], [5,6]]

我想检查列表 b 的第二个元素等于它的第一个元素时的条件。

len_b = len(b);
for i in range(0, len_b):
    if b[i][1] == b[0][i]:
        print 'anything'

但是,每当我执行此操作时,我都会遇到 IndexError: list index out of range.

最佳答案

Hackaholic 的解决方案解决了这个问题,但是 Pythonic 的方法是使用元组解包而不是索引:-

>>> b = [[1,2], [1,3], [2,4], [2,5], [3,4], [3,5], [4,6], [5,6]]
>>> for x, y in b:                                              
        if x == y:
            print 'anything'

关于python - 在 Python 中搜索列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27145480/

相关文章:

python - 从 python 有序字典中删除一个键的复杂性

python - 退出 ipython

python - PEP8 E112 不应该出现缩进错误?

python - 我可以在单个 Python pytest 方法中处理多个断言吗?

python-2.7 - OpenCV cv2.matchTemplate崩溃:python.exe中0x74B5E4E4处未处理的异常:0xC0000005

python-2.7 - python : how to remove only first word from a string

python - 组合 2 个不同元组的值的最佳方法

python - Pandastable 表无法使用向下键自动向下滚动

python - 两个数据库表之间的关系

python - "no matching architecture in universal wrapper"导入pygame时