使用整数Python3将数字字符串列表转换为元组

时间:2018-10-19 02:17:18

标签: python string list tuples

示例:

我的系统上保存了一个名为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循环,但是我什么都找不到。 任何帮助将不胜感激!

4 个答案:

答案 0 :(得分:0)

如果要获得与您提到的输出完全相同的输出,可以在,上拆分每一行并将其存储在元组中,

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'])

答案 1 :(得分:0)

与他人达成共识,在这种情况下最好使用词典,但这应该可以实现您的目标:

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'])]

答案 2 :(得分:0)

假定文本与您在问题中输入的文本完全相同:

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'])
]

首先,我们抓住所有在两个单引号之间包含一些内容的行。然后取出单引号,并用逗号将其分隔开来创建一个数组。最后,使用第一个元素和第二个元素到最后一个元素的子数组创建一个元组。

答案 3 :(得分:0)

您可以尝试以下方法:

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

它将以您描述的格式返回元组列表。