簡體   English   中英

從 str 列表(從文件)中獲取項目並制作成 int?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM