简体   繁体   English

在Python上将列表转换为整数

[英]converting a list to integer on python

I was trying to run a code that I wrote the code reads lines on txt file so my text file looks like (i've 20 lines) 我试图运行一个代码,我编写的代码读取txt文件中的行,因此我的文本文件看起来像(我有20行)

['39', '40', '39', '38', '35', '38', '39', '39', '42', '37', '40', '41', '37', '39', '39', '40', '38', '40', '39', '40'] ['39','40','39','38','35','38','39','39','42','37','40','41',' 37”,“ 39”,“ 39”,“ 40”,“ 38”,“ 40”,“ 39”,“ 40”]

['39', '40', '39', '38', '36', '39', '40', '39', '42', '38', '40', '41', '38', '39', '39', '40', '38', '40', '39', '41'] ['39','40','39','38','36','39','40','39','42','38','40','41',' 38”,“ 39”,“ 39”,“ 40”,“ 38”,“ 40”,“ 39”,“ 41”]

['39', '40', '40', '38', '36', '39', '40', '39', '43', '38', '40', '41', '38', '39', '39', '40', '38', '40', '39', '41'] ['39','40','40','38','36','39','40','39','43','38','40','41',' 38”,“ 39”,“ 39”,“ 40”,“ 38”,“ 40”,“ 39”,“ 41”]

i wrote this script to have a new file that looks like this 我写这个脚本有一个看起来像这样的新文件

39 40 39 38 35 38 39 39 42 37 40 41 37 39 39 40 38 40 39 40 39 40 39 38 35 38 39 39 42 37 40 41 37 39 39 40 38 40 39 40

39 40 39 38 36 39 40 39 42 38 40 41 38 39 39 40 38 40 39 41 39 40 39 38 36 39 40 39 42 38 40 41 38 39 39 40 38 40 39 41

39 40 40 38 36 39 40 39 43 38 40 41 38 39 39 40 38 40 39 41 39 40 40 38 36 39 40 39 43 38 40 41 38 39 39 40 38 40 39 41

the script that i wrote is this one 我写的脚本就是这个

    #!/usr/bin/python3
# -*- coding: utf-8 -*-

fichier=open("data.txt", "r")
#resultat=open("data_entier.txt", "w")

j=0;

while j < 20:
    lignes= fichier.readline()
    for i in range(len(lignes)):
         lignes[i] = int(lignes[i])

    print(lignes))

    j+=1

fichier.close()

the error that I get is this one 我得到的错误是这个

ValueError: invalid literal for int() with base 10: '[' ValueError:int()以10为底的无效文字:“ [”

The problem is that when you read in readline from your file, you will have a line 问题是,当您从文件中读取readline ,将有一行

"['39', '40', '39', '38', '35', '38', '39', '39', '42', '37', '40', '41', '37', '39', '39', '40', '38', '40', '39', '40']\n"

As you can see, the first item in your string is [ . 如您所见,字符串中的第一项是[ So, you don't actually have the numbers structured as you are expecting. 因此,您实际上并没有按预期的方式组织数字 Instead, since you seem to already have a list structure represented as a string, consider using literal_eval from ast : 相反,因为你似乎已经表示为一个字符串列表结构,可以考虑使用literal_evalast

>>> d = literal_eval(d)
>>> d
['39', '40', '39', '38', '35', '38', '39', '39', '42', '37', '40', '41', '37', '39', '39', '40', '38', '40', '39', '40']

Now you actually have a list of strings. 现在,您实际上有了一个字符串列表 Now you can proceed modifying that to your ints. 现在,您可以将修改为自己的整数。 As a simple process, you can then do something like this: 作为一个简单的过程,您可以执行以下操作:

>>> converted_to_ints = map(int, d)
>>> print(list(converted_to_ints))
[39, 40, 39, 38, 35, 38, 39, 39, 42, 37, 40, 41, 37, 39, 39, 40, 38, 40, 39, 40]

Note, when it comes to using map in Python 3 you get a map object , which returns an iterator. 注意,在Python 3中使用map ,您会得到一个map对象 ,该对象返回一个迭代器。 So, if you need the list , this is why list is called when printing. 因此,如果需要list ,这就是为什么在打印时调用list原因。 You can read about it here: 你可以在这里读到它:

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

Area of Improvement 改进领域

Based on the contents of the file you are reading, it would be best to not structure the data like this. 根据您正在读取的文件的内容, 最好不要像这样构造数据。 Instead, what should be done is not setting the data as a list representation in to the file, but just the contents of the list. 相反,应该做的不是将数据设置为文件的列表表示形式,而只是将列表的内容设置。 This avoids having to perform the above solution, and instead, a simple: 这样可以避免执行上述解决方案,而只需执行以下简单操作即可:

with open('file.txt') as f:
  data = f.read().splitlines() # will remove newline character
  for line in data:
      # perform operations

would suffice. 就足够了。

You are not evaluating the line as a list: every line is just a string that happens to start with a '[' . 没有将行作为列表进行评估:每行只是一个以'['开头的字符串。 So you are iterating over the characters of the line. 因此,您正在遍历该行的字符

If the file is like you describe it however, you can easily evaluate the line with ast.literal_eval : 如果文件像您描述的那样,则可以使用ast.literal_eval轻松评估该行:

from ast import literal_eval

with open("data.txt", "r") as fichier:
    for line,_ in zip(fichier,range(20)):
        the_list = literal_eval(line)
        the_list = [int(x) for x in the_list]
        print(the_list))

We here used zip as a way to obtain the first 20 lines. 我们在这里使用zip作为获取前20行的方法。 If you want to process all the lines, you can simply use: 如果要处理所有行,则可以简单地使用:

with open("data.txt", "r") as fichier:
    for line in fichier:
        the_list = literal_eval(line)
        the_list = [int(x) for x in the_list]
        print(the_list))

You're reading a line, so you can simply replace the chars you don't want. 您正在阅读一行,因此只需替换不需要的字符即可。

string = "['39', '40', '39', '38', '35', '38', '39', '39', '42', '37', '40', '41', '37', '39', '39', '40', '38', '40', '39', '40']"
s = string.replace(',','').replace('[','').replace(']','').replace("'","")
print s
#output: 39 40 39 38 35 38 39 39 42 37 40 41 37 39 39 40 38 40 39 40

Although in this case the ast.literal_eval solutions presented by idjaw and Willem Van Onsem seem as an obvious best fit, let me present another solution: 尽管在这种情况下,idjaw和Willem Van Onsem提出的ast.literal_eval解决方案似乎是最合适的选择,但让我提出另一个解决方案:

numbers_text = "['39', '40', '39', '38', '35', '38', '39', '39', '42', '37', '40', '41', '37', '39', '39', '40', '38', '40', '39', '40']"

Instead of chaining multiple replace operations, you can use str.translate to get rid of multiple characters in one pass, by providing the third argument to str.maketrans : 通过给str.maketrans提供第三个参数,您可以使用str.translate多个字符,而不是链接多个replace操作:

If there is a third argument, it must be a string, whose characters will be mapped to None in the result. 如果有第三个参数,则必须是一个字符串,其字符将在结果中映射为None

Afterwards, we can either use a simple list comprehension to convert the separate numbers from str to int : 然后,我们可以使用简单的列表推导将单独的数字从str转换为int

numbers_int = [int(x) for x in numbers_text.translate(str.maketrans("","","[',]")).split()]

Or make use of map : 或利用map

numbers_int = list(map(int, numbers_text.translate(str.maketrans("","","[',]")).split()))

Both will result in a new list of int : 两者都会产生一个新的int list

[39, 40, 39, 38, 35, 38, 39, 39, 42, 37, 40, 41, 37, 39, 39, 40, 38, 40, 39, 40]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM