简体   繁体   English

Python 将字符串转换为 Int 列表

[英]Python convert string to list of Int

I have a text file with multiple lines of numbers, Using the code below produces the result below我有一个包含多行数字的文本文件,使用下面的代码会产生下面的结果

Code:代码:

with open('servers.txt') as x:
            b = [line.strip() for line in x]

Result:结果:

['867121767826980894', '828966373161828373']

I need to convert this to below so 867121767826980894 is an int and 828966373161828373 also an int separated by comma's我需要将其转换为以下,因此 867121767826980894 是一个 int 和 828966373161828373 也是一个用逗号分隔的 int

[867121767826980894, 828966373161828373]

Convert string to int with the int() function:使用int() function 将字符串转换为 int:

mylist = [int(item) for item in mylist]

Now the list contains integers and not strings.现在列表包含整数而不是字符串。
To be sure that no error occurs during conversion, use try-except :为确保在转换过程中不会发生错误,请使用try-except

for x in range(0, len(mylist)):
    try:
        mylist[x] = int(mylist[x])
    except:
        print("Error while converting item %s" % x)

The better solution that fits for your case is this one:适合您的情况的更好的解决方案是这个:

with open('servers.txt') as x:
    try:
        b = [int(line.strip()) for line in x]
    except:
        print("Error while converting line", line)

Hope those solutions help you.希望这些解决方案对您有所帮助。 :) :)

Look into this article: https://www.geeksforgeeks.org/python-converting-all-strings-in-list-to-integers/查看这篇文章: https://www.geeksforgeeks.org/python-converting-all-strings-in-list-to-integers/

for i in range(0, len(b)):
    b[i] = int(test_list[b])

            OR
b = [int(i) for i in b]

Or You could forego the whole problem and use the builtin csv reader to read the file as tsv, or well I guess ssv in this case或者您可以放弃整个问题并使用内置的 csv 阅读器将文件读取为 tsv,或者在这种情况下我猜是 ssv

import csv
with open( "servers.txt" ) as f:
    csv.reader( f, delimiter=" " )

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

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