【问题标题】:Is there a way to read only a single integer from a line of integers in Python 3.x?有没有办法从 Python 3.x 中的一行整数中只读取一个整数?
【发布时间】:2019-06-19 10:08:14
【问题描述】:

我的最终目标是:给定一个数字列表,创建地图,其中键是数字,值是它在给定列表中的频率。

假设我有一个输入,我想通过标准输入提供给我的程序。它是包含一定数量整数的单行。示例:

 12 1 4 5 10 87

有没有办法一次只能读取一个整数?到目前为止,我一直在一口气输入,根据空格分隔符将其拆分,然后将每个元素的字符串转换为整数,如下所示:

arr = input().split() //Take input
myArr = list(map(lambda x : int(x), arr)) //Map each string element to it's integer counterpart.

由于我只想创建一个地图,因此一次读取整个输入并将其保存在内存中对我来说是不必要的。 有没有更好的方法来做到这一点,我一次只能读取 1 个整数并构建我的地图,而不必一次完全读取列表?

谢谢!

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您正在寻找的是Counter。 Counter 创建一个包含出现次数的字典。你可以像下面那样做。

    from collections import Counter
    
    print(Counter(map(int, input().split())))
    

    输出:

    12 1 4 5 10 87
    Counter({12: 1, 1: 1, 4: 1, 5: 1, 10: 1, 87: 1})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 2014-03-23
      相关资源
      最近更新 更多