如何将列表中的项目转换为元组?

时间:2018-04-22 02:05:48

标签: python python-3.x csv dictionary

我创建了这个函数,它接受文件的内容并将其翻译成字典。我有正确的格式,我似乎无法弄清楚如何将列表内容变成元组。

这是我的功能,它没有让元组部分失效:

def read(file:open) -> dict:
    file_lines = file.read().splitlines()
    result_dict = dict()
    for string in file_lines:
        splitted = string.replace(':', ';')
        new_splitted = splitted.split(';')
        client_name = new_splitted[0]
        new_splitted = new_splitted[1:]
        result_dict[client_name] = new_splitted
    return result_dict

例如,我怎样才能使它成为一个元组?我尝试使用tuple(),((x,)),似乎没有任何工作。谢谢!

4 个答案:

答案 0 :(得分:0)

您可以将构造元组与with open("portfolio1.txt", 'r') as f: d = dict() for line in f: line = line.rstrip() key, prevalue = line.split(':') d[key] = [tuple(item.split(',')) for item in prevalue.split(';')] print(d) 一起使用。

net.ipv4.ip_forward

答案 1 :(得分:0)

这是您构建逻辑的另一种方法。此方法还处理字符串到整数的转换。

def splitter(item):
    split = item.split(',')
    return (split[0], int(split[1]), int(split[2]))

d = {}

with open('portfolio1.txt', 'r') as f:
    for line in f:
        k, vals = line.rstrip().split(':')
        v = [splitter(x) for x in vals.split(';')]
        d[k] = v

结果:

{'Alan': [('Intel', 20, 10),
          ('Dell', 10, 50),
          ('Apple', 80, 80),
          ('Dell', -10, 55)],
 'Barb': [('Intel', 20, 40),
          ('Intel', -10, 45),
          ('IBM', 40, 30),
          ('Intel', -10, 35)],
 ...

答案 2 :(得分:0)

您可以使用pandas。只需确保之前替换:的所有;

df = pd.read_csv(f, sep = ";", header = None)
df.set_index(0).apply(lambda k: [tuple(str(j).split(",")) for j in k], 1).T.to_dict(orient="list")

{'Alan': [('Intel', '20', '10'),
  ('Dell', '10', '50'),
  ('Apple', '80', '80'),
  ('Dell', '-10', '55')],
 'Barb': [('Intel', '20', '40'),
  ('Intel', '-10', '45'),
  ('IBM', '40', '30'),
  ('Intel', '-10', '35')],
 'Carl': [('Intel', '30', '40'),
  ('Dell', '20', '50'),
  ('Intel', '-10', '60'),
  ('Apple', '20', '55')],
 'Dawn': [('Apple', '40', '80'),
  ('Apple', '40', '85'),
  ('Apple', '-40', '90'),
  ('nan',)]}

答案 3 :(得分:0)

如下所示,

使用元组(x.split(,))

def read_db(file:open) -> dict:
    file_lines = file.read().splitlines()
    result_dict = dict()
    for string in file_lines:
        splitted = string.split(':')
        client_name = splitted[0]
        new_splitted = splitted[1]
        parts = new_splitted.split(';')
        # tuple(x.split(','))
        parts_tuple = [tuple(x.split(',')) for x in parts]
        result_dict[client_name] = parts_tuple

输出

{
    'Carl': [('Intel', '30', '40'), ('Dell', '20', '50'), ('Intel', '-10', '60'), ('Apple', '20', '55')],
    'Barb': [('Intel', '20', '40'), ('Intel', '-10', '45'), ('IBM', '40', '30'), ('Intel', '-10', '35')],
    'Alan': [('Intel', '20', '10'), ('Dell', '10', '50'), ('Apple', '80', '80'), ('Dell', '-10', '55')],
    'Dawn': [('Apple', '40', '80'), ('Apple', '40', '85'), ('Apple', '-40', '90')]
}