简体   繁体   English

如何在Python中打印列表的特定元素?

[英]How to print specific elements of a list in Python?

I am trying to print the nth value of a list, in this case an integer. 我正在尝试打印列表的第n个值,在这种情况下为整数。 However every time I get the entire list as output: 但是,每次我得到整个列表作为输出时:

[1, 2, 3]

from this code: 从此代码:

numbers1 = []
numbers1.insert(0, list(map(int, input().split(" "))))


print(numbers1[0])

What am I doing wrong here? 我在这里做错了什么?

I don't understand why it isn't printing the first element, numbers1[0]. 我不明白为什么它不打印第一个元素,numbers1 [0]。

You're inserting a list onto a list so your list actually looks like this: 您正在将列表插入列表,因此列表实际上如下所示:

[ [1, 2, 3] ]

What you want can be accomplished by doing: 您可以通过执行以下操作来实现:

numbers1 = list(map(int, input().split(" ")))

or 要么

numbers1.extend(list(map(int, input().split(" "))))

However, I would advise against using map with input in this case because it obfuscates your input and you don't usually want to do that. 但是,在这种情况下,我建议不要将map与输入配合使用,因为它会混淆您的输入,并且您通常不想这样做。 Instead, try this: 相反,请尝试以下操作:

userInput = input()
numbers1.extend( [int(s) for s in userInput.split(" ")] )

This code does the same thing but as a list comprehension, which avoids the call to map and the call to list , reducing overhead while improving readability. 该代码的作用与列表理解相同,它避免了对map的调用和对list的调用,从而在提高可读性的同时减少了开销。 This is also more Pythonic IMHO. 这也是Pythonic的恕我直言。

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

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