首页 > 解决方案 > 如何在某些索引处显示包含某些元素的列表?

问题描述

如果所述列表在某些位置包含某些元素,我一直在尝试让 Python 2.7 显示列表(或字符串、元组等)中的任何内容。

假设我知道对于列表ll[1]应该是3l[2]应该是1l[5]应该是5。如果这些条件成立,我想打印l,但我坚持编写contains_at函数。

indexes = (1, 2, 5)
elements = (7, 1, 8)

l1 = [2, 7, 1, 8, 2, 8, 1]
l2 = [3, 1, 4, 1, 5, 9, 2, 6, 5]


def print_if_contains_at(l, idxs, elts):
    # some function that returns True if I should print the list
    if contains_at(l, idxs, elts):
        print(l)

# prints the entire list l1
print_if_contains_at(l1, indexes, elements)


# prints nothing, since l2 doesn't contain the correct pattern of elements
print_if_contains_at(l2, indexes, elements)

标签: pythonindexing

解决方案


我能想出的最接近的解决方案是做同样工作的最刚性和最不灵活的解决方案。这适用于少量列表,但是编写无数步骤会很详尽。

a = input('Enter the string')

b,c,d = input('Enter the the three index elements you are looking for')

    if a in b[0:3]:

                  print(string)

推荐阅读