繁体   English   中英

如何显示包含特定索引处特定元素的列表?

[英]How to display a list containing certain elements at certain indexes?

如果所述列表在某些位置包含某些元素,我一直试图让 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)

我能想出的最接近的解决方案是完成相同工作的最严格和最不灵活的解决方案。 这适用于少量列表,但是编写无数步骤将是详尽无遗的。

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)

这是一个有效的contains_at 通读关于列表推导式zip 的教程以了解它在做什么。

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 contains_at(l, idxs, elts):
    return all(l[idx] == elt for idx, elt in zip(idxs, elts))


def print_if_contains_at(l, idxs, elts):
    if contains_at(l, idxs, elts):
        print(l)


print_if_contains_at(l1, indexes, elements)
print_if_contains_at(l2, indexes, elements)

# prints only [2, 7, 1, 8, 2, 8, 1]

在线试试吧!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM