【问题标题】:How can I convert the items in the list into a tuple?如何将列表中的项目转换为元组?
【发布时间】:2018-10-02 08:45:55
【问题描述】:

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

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

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,)),但似乎没有任何效果。谢谢!

【问题讨论】:

  • tuple(x.split(','))

标签: python python-3.x csv dictionary


【解决方案1】:

您可以将构造元组与tuple(sequence) 一起使用。

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)

【讨论】:

    【解决方案2】:

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

    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)],
     ...
    

    【讨论】:

      【解决方案3】:

      您可以使用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',)]}
      

      【讨论】:

        【解决方案4】:

        如下改变,

        使用元组(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')]
        }
        

        【讨论】:

        • 我怎样才能使整数值是整数而不是字符串?例如,我想要 30 而不是“30”
        • 像 jpp 的回答一样使用splitter
        • 我怎样才能将它整合到您更改的解决方案中?感觉变化太大了
        • parts_tuple = [splitter(x) for x in parts] 而不是parts_tuple = [tuple(x.split(',')) for x in parts] 否则最好使用jpp的解决方案
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-10
        • 1970-01-01
        • 2010-12-11
        • 2015-09-24
        • 1970-01-01
        相关资源
        最近更新 更多