如何在python中打印出列表的某些元素?

时间:2019-01-27 13:44:02

标签: python

所以我有一个列表li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],我只想打印出属于算术序列6n - 5(第1,第7和第13)的元素。

如果我有一个包含n个元素的列表,该怎么办?

6 个答案:

答案 0 :(得分:3)

您可以简单地说

print([x for x in li if x % 6 == 1])

或者,如果您只是想要序列而又不想为创建li而烦恼,

print([6*n-5 for n in range(1, (13+5)//6+1)])

答案 1 :(得分:0)

使用代码:

li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 
new=[]
for i in li:
    if int((i+5)/6)==((i+5)/6): 
    #You can also use
    #if ((i+5)/6).is_integer():
         new.append(i)

我试图使其尽可能简单。

希望它会有所帮助:)

答案 2 :(得分:0)

li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

for n in range(1,len(li)+1): #choose n such that it is length of the list since it cant have more values than the number of values in the list.
    for i in li:
        if (6*n - 5) == i:
           print(i)

希望这会有所帮助

谢谢

迈克尔

答案 3 :(得分:0)

据我了解,您希望元素的位置由序列生成。因此,您需要数组长度为n的元素,其索引来自序列函数6x-5

注意:我假设您正在使用基于1的索引,这意味着,当您说列表中的第1个元素时,您打算获得1不是< / strong> 2

n = 13
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

# generate the sequence till n
seq = []
x = 1
while 6*x-5 <= n:
    seq.append(6*x-5)
    x += 1

# Print the elements from the sequence:
for idx in seq:
    print(li[idx-1])

# If you want to store it in another list:
li2 = [li[idx-1] for idx in seq]

下面是上述代码的一种更通用,更有效的方法:

n = 13
li = list(range(1, n+1)) # More easy to write

# More efficient way is to create a generator function
def get_seq(n):
    x = 1
    while 6*x-5 <= n:
        yield 6*x-5
        x += 1

# Get the generator object
seq = get_seq(n)

# Print the elements from the sequence:
for idx in seq:
    print(li[idx-1])

# Want to store it in another list:
seq = get_seq(n) # Don't forget to get a new generator object.
li2 = [li[idx-1] for idx in seq]

两个摘要的输出:

1
7
13

希望答案会有所帮助,并消除其他人的困惑;)

答案 4 :(得分:0)

您可以简单地为任何n生成序列。

例如:

n = 10
print([ 6*x - 5 for x in range(1,n)])

输出:

[1, 7, 13, 19, 25, 31, 37, 43, 49]
>>>  [Finished in 0.2s]

但是,如果您只想过滤现有列表li:

li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print([ x for x in li if x % 6 == 1 ])

输出:

[1, 7, 13]
>>> 
[Finished in 0.3s]

答案 5 :(得分:0)

li[1]为2,li[7]为8,索引为13的元素超出范围。

li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 

for num, i in enumerate(li):
   if ((num + 5)/6).is_integer():
       print(i)
# 2
# 8

如果要以索引1开头,请将start=1添加到enumerate()函数中。

for num, i in enumerate(li, start=1):
   if ((num + 5)/6).is_integer():
       print(i)
# 1
# 7
# 13