【问题标题】:Python basics: How to read N ints until '\n' is found in stdin [duplicate]Python基础知识:如何读取N个整数,直到在标准输入中找到'\ n' [重复]
【发布时间】:2010-02-17 23:35:09
【问题描述】:

如何从输入中读取 N 个ints,并在找到\n 时停止读取?另外,如何将它们添加到我可以使用的数组中?

我正在从 C 语言中寻找类似的东西,但在 python 中

while(scanf("%d%c",&somearray[i],&c)!=EOF){
    i++;
    if (c == '\n'){
        break;
    }
}

【问题讨论】:

    标签: python stdin


    【解决方案1】:

    在 Python 2 中:

    lst = map(int, raw_input().split())
    

    raw_input() 从输入中读取整行(在\n 处停止)作为字符串。 .split() 通过将输入拆分为单词来创建字符串列表。 map(int, ...) 从这些单词中创建整数。

    在 Python 3 中,raw_input 已重命名为 inputmap 返回的是迭代器而不是列表,因此需要进行一些更改:

    lst = list(map(int, input().split()))
    

    【讨论】:

      【解决方案2】:

      Python 中没有直接等效的 scanf,但这应该可以工作

      somearray = map(int, raw_input().split())
      

      在 Python3 中,raw_input 已重命名为 input

      somearray = map(int, input().split())
      

      这是一个细分/解释

      >>> raw=raw_input()              # raw_input waits for some input
      1 2 3 4 5                        # I entered this
      >>> print raw
      1 2 3 4 5                            
      >>> print raw.split()            # Make a list by splitting raw at whitespace
      ['1', '2', '3', '4', '5']            
      >>> print map(int, raw.split())  # map calls each int() for each item in the list
      [1, 2, 3, 4, 5]
      

      【讨论】:

        猜你喜欢
        • 2011-06-10
        • 1970-01-01
        • 2023-03-06
        • 2021-12-11
        • 2018-02-25
        • 2012-01-01
        • 2020-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多