【问题标题】:What does int(n) for n mean?n 的 int(n) 是什么意思?
【发布时间】:2020-02-23 20:52:26
【问题描述】:

为了将输入放入列表中:

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

有人能解释一下'int(n) for n in'是什么意思吗?

如何改进这个问题?

【问题讨论】:

  • 代码所做的是,它从用户输入中获取整数作为数字,然后 .split() 函数将其转换为列表
  • 小澄清 - 代码行接受用户输入,将其拆分为 n 个单独的部分(假设这些是数字),将表示为字符串的每个数字转换为表示为整数的数字,然后放入列表中的所有这些数字,使用列表推导(这就是外括号的作用)。
  • 也许也很有趣,为什么你应该尽可能使用推导式(不仅仅是因为它看起来不错......):stackoverflow.com/questions/30245397/…
  • 谢谢大家!你的回答太全面了!谢谢! @MrFuppes

标签: python-3.x


【解决方案1】:

整个表达式称为列表理解。这是一种更简单的 Pythonic 方法来构建遍历列表的 for 循环。

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

给定您的代码:

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

假设您运行提供的代码,您会收到输入提示:

Enter numbers: 10 8 25 33

现在发生的情况是,Python 的 input() 函数返回一个字符串,如下所述:

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

所以代码现在基本上变成了这样:

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

现在 split() 函数从由给定字符分隔的字符串中返回一个元素数组,作为字符串。

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

所以现在你的代码变成了:

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

这段代码现在相当于:

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

int(n) 方法将参数 n 从字符串转换为 int 并返回 int。

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

【讨论】:

    【解决方案2】:

    例如input('Enter numbers: ').split() 返回一个字符串数组,如['1', '4', '5']

    int(n) for n in 将循环遍历数组并将每个 n 转换为整数,而 n 将是数组的相应项。

    【讨论】:

      【解决方案3】:

      让我们尝试通过一段简单的代码来理解这个列表推导表达式,这意味着同样的事情。

      nums = input('Enter numbers: ') # suppose 5 1 3 6 
      
      nums = nums.split() # it turns it to ['5', '1', '3', '6']
      
      numbersList = [] # this is list in which the expression is written
      
      for n in nums: # this will iterate in the nums.
          number = int(n) # number will be converted from '5' to 5
          numbersList.append(number) # add it to the list
      
      print(numbersList) # [5, 1, 3, 6]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-04
        • 1970-01-01
        • 2017-12-29
        • 2015-09-02
        • 2017-07-27
        • 2010-12-26
        • 1970-01-01
        相关资源
        最近更新 更多