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

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

python 3.x - What does int(n) for n mean?

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...