Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In order to put the input into a list:

  numbersList = [int(n) for n in input('Enter numbers: ').split()]

Can someone explain what does 'int(n) for n in' mean?

How do I improve this question?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
298 views
Welcome To Ask or Share your Answers For Others

1 Answer

The entire expression is referred to as a List Comprehension. It's a simpler, Pythonic approach to construct a for loop that iterates through a list.

https://www.pythonforbeginners.com/basics/list-comprehensions-in-python

Given your code:

numbersList = [int(n) for n in input('Enter numbers: ').split()]

Lets say you run the code provided, you get a prompt for input:

Enter numbers: 10 8 25 33

Now what happens is, Python's input() function returns a string, as documented here:

https://docs.python.org/3/library/functions.html#input

So the code has now essentially become this:

numbersList = [int(n) for n in "10 8 25 33".split()]

Now the split() function returns an array of elements from a string delimited by a given character, as strings.

https://www.pythonforbeginners.com/dictionary/python-split

So now your code becomes:

numbersList = [int(n) for n in ["10", "8", "25", "33"]]

This code is now the equivalent of:

numbersAsStringsList = ["10", "8", "25", "33"]
numberList = []
for n in numbersAsStringsList:
    numberList.append(int(n))

The int(n) method converts the argument n from a string to an int and returns the int.

https://docs.python.org/3/library/functions.html#int


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...