簡體   English   中英

將數字字符串列表轉換為帶有整數的元組 Python3

[英]Converting a list of strings of numbers to tuples with integers Python3

例子:

我的系統上保存了一個名為data.txt的文件。 該文件包含以下信息:

'Noah,14,233,66,21,88,42'
'Robert,34,11,667,2,785,23'
'Jackson,85,22,73,12,662,5'

等等,

我的問題是我怎樣才能把它變成一個帶整數的元組?,所以這是需要的:

('Noah', [14,233,66,21,88,42] ),
('Robert', [34,11,667,2,785,23] )

我假設您必須為每一行使用 for 循環,但我無法弄清楚。 任何幫助,將不勝感激!

如果您想要完全相同的輸出,您可以在 上拆分每一行,並將其存儲在一個元組中,

x = 'Noah,14,233,66,21,88,42'
# split string on , 
x = x.strip().split(',')
# x[0] is name, while x[1]....x[n] are numbers
y = (x[0], x[1:])
print(y)

輸出,

('Noah', ['14', '233', '66', '21', '88', '42'])

顯然你需要先分別從文件中讀取每一行,所以,

with open("file_name", "r") as file:
    for line in file:
      line = line.strip().split(',')
      output = (line[0], line[1:])

將輸出,

('Noah', ['14', '233', '66', '21', '88', '42'])
('Robert', ['34', '11', '667', '2', '785', '23'])
('Jackson', ['85', '22', '73', '12', '662', '5'])

同意其他人的觀點,字典可能最適合這種情況,但這應該可以實現您的目標:

data= """Noah,14,233,66,21,88,42
Robert,34,11,667,2,785,23
Jackson,85,22,73,12,662,5"""

[(row.split(',')[0], row.split(',')[1:]) for row in data.split('\n')]

輸出:

[('Noah', ['14', '233', '66', '21', '88', '42']),
('Robert', ['34', '11', '667', '2', '785', '23']),
('Jackson', ['85', '22', '73', '12', '662', '5'])]

假設文本與您在問題中所擁有的完全相同:

import re

input = """
'Noah,14,233,66,21,88,42'

'Robert,34,11,667,2,785,23'

'Jackson,85,22,73,12,662,5'
"""

lines = re.findall("'.*'", input) # Find lines which contain text between single quotes

tuples = []

for line in lines:
  line = line.replace("'", "").split(",") # Remove single quotes, split by comma
  tuples.append((line[0], line[1:])) # Add to tuple

print(tuples)

哪個會打印:

[
  ('Noah', ['14', '233', '66', '21', '88', '42']), 
  ('Robert', ['34', '11', '667', '2', '785', '23']), 
  ('Jackson', ['85', '22', '73', '12', '662', '5'])
]

首先,我們獲取所有包含在兩個單引號之間的行。 然后取出單引號並通過用逗號將其拆分來創建一個數組。 最后用第一個元素和第二個到最后一個元素的子數組創建一個元組。

你可以試試這個:

   with open(data.txt, 'r') as f:
        lines = [(line.strip().split(',')[0], line.strip().split(',')[1:])for line in f]
   print(lines)

它將以您描述的格式返回元組列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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