Python从文件中读取东西,C ++风格

时间:2017-04-04 17:14:57

标签: python file input

我有这个C ++

int n = 0;
file >> n;

for (int i = 0; i < n; i++) file >> array[i];

etc.

我如何在Python中简洁地编写它?

这是Python:

string = string.lstrip()

n = 0
for c in string:
  if not c.isdigit():
    break
  n = n * 10 + int(c)

for i in range(n):
  string = string.lstrip()
  for c in string:
    if not c.isdigit():
      break
    array[i] = array[i] * 10 + int(c)

我认为Python应该比C ++更具“表现力”。

2 个答案:

答案 0 :(得分:1)

不要手动解析字符串中的整数。 Python完全有能力为你做到这一点:

>>> s = "12345"
>>> i = int(s)
>>> print(i)
12345

这已经清理了大部分代码:

string = string.lstrip()
n = int(string)

for i in range(n):
  string = string.lstrip()
  array[i] = int(string)

我没有看到任何围绕琴弦移动的逻辑,所以我假设你已经把这些碎片留下了。你不清楚这些整数的确切区别是什么(你的代码说&#34;任何不是数字&#34;),所以我反而假设它是&#39;以空格分隔。

Python可以通过str中的一种方法为您分割这些字符串:split

>>> s = "1 2\n3\t4 5"  # Notice: all kinds of whitespace here.
>>> arr = s.split()  # By default, split will split on whitespace.
>>> print(arr)
['1', '2', '3', '4', '5']

请注意,拆分将值保留为字符串。这意味着我们还没有完成,我们还必须将每个单独的元素转换为我之前演示过的整数。

在这里,我将使用名为list comprehensions的Python功能:

>>> s = "1 2\n3\t4 5"
>>> arr = [int(n) for n in s.split()]
>>> print(arr)
[1, 2, 3, 4, 5]

当人们提到“表达性”时,人们正在谈论这个问题。 Python :)这会将您编写的所有代码转换为单行代码。但是,这假设您的数据已经在字符串中。您似乎正在阅读文件,因此需要更多工作才能使其正常运行...

arr = []  # Empty list. 
with open("path/to/file.txt") as f:
    for line in f:  # Will read all lines.
        arr += [int(x) for x in line.split()]
# Use arr...

...假设您在一行中有多个整数。相反,如果你在每一行都有一个int,你的代码会变得更简单:

with open("path/to/file.txt") as f:
    arr = [int(line) for line in f]  # Will read all lines.
# Use arr...

然而,这仍然不是解决原始问题的完全解决方案......但我希望它不会受到教育。 FWIW,这就是我如何解决您的特定问题:

with open("path/to/file.txt") as f:
    ints_of_f = (int(line) for line in f)  # A *GENERATOR*, not a *LIST*.
    n = next(ints_of_f)
    arr = [next(ints_of_f) for _ in range(n)]  # _ is a throwaway variable.

最后,这里有great talk关于如何写&#34;美丽,富有表现力的&#34; Python代码。

答案 1 :(得分:1)

io class告诉我们文件对象有哪些方法(open()返回的东西)。我没有看到像“读取单词”或“读取int”的内容。

我打算说编写一些这样做的小函数很简单,但它变成了一个4小时的远征,变得相当大,只是Stack Overflow答案中的一个例子。我已经在Github上发布了它:https://github.com/lgommans/OpenSesame

您需要的文件只是open_sesame.py。基本用法是:

from open_sesame import OpenSesame

myfile = OpenSesame("data.txt")
records = myfile.int()
for i in range(0, records):
    array.append(myfile.number())

我尝试对代码进行评论并使其非常清晰,因此如果您想要进行修改或查看它的作用,这应该是可以理解的。