[英]Take items from str list (from file) and make into int?
我正在尝试打开一个文件,将内容转换为字符串列表,然后从该列表中的特定位置获取项目并使它们成为可用的整数。 有没有办法做到这一点?
我目前在哪里:
#I want to get the 3 and 9 into an x and a y integer.
#File contents:
#Bob
#Male
#43
#3, 9
with open("person.csv", "r") as file:
mylist = [int(x) for x in file.read().split()]
print (mylist)
目前得到:ValueError:int()的无效文字,基数为10:'Bob'
编辑:我知道 Bob 和 Male 是字符串,这就是问题所在。 我需要在这个文件中存储字符串和整数,只需将整数拉到底部 (3,9),然后将该特定数字拆分为两个整数。 很抱歉有任何混淆。
使用 csv.reader,这将让您选择分隔符,例如“,” - 不要忘记为此import csv
。
#I want to get the 3 and 9 into an x and a y integer.
#File contents:
#Bob
#Male
#43
#3, 9
import csv
with open("person.csv", "r") as file:
rows = list(csv.reader(file, delimiter=','))
x, y = rows[3]
print(x, y)
您正在尝试将字符串"Bob"
转换为 integer。 您需要忽略无法转换为整数的值。
而不是mylist = [int(x) for x in file.read().split()]
,你应该这样做:
mylist = file.read().split()
result = []
for x in mylist:
try:
n = int(x)
result.append(n)
except ValueError:
# cannot convert to int
pass
当然,这不会立即对3, 9
起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.