【问题标题】:Extracting a list of tuples from a list of dictionaries, some values separated with commas and single quotes and some without从字典列表中提取元组列表,一些值用逗号和单引号分隔,一些没有
【发布时间】:2020-12-23 16:38:18
【问题描述】:

我有一个字典列表,每个字典包含:

  • 名字
  • 中间名
  • 姓氏
  • 标题
  • 地址
  • 电子邮件地址
  • 忠诚度计划 对于一个客户。其中一些信息可能会丢失
segment = [{'first-name': 'Elsa', 'last-name': 'Frost', 'title': 'Princess', 'address': '33 Castle Street, London', 'loyalty-program': 'Gold'}, {'first-name': 'Anna', 'last-name': 'Frost', 'title': 'Princess', 'loyalty-program': 'Platinum'}, {'first-name': 'Harry', 'middle-name': 'Harold', 'last-name': 'Hare', 'title': 'Mr', 'email-address': 'harry.harold@hare.name', 'loyalty-program': 'Silver'}]

对于有物理地址的客户,我需要提取一个元组列表。每个元组代表一个客户,并包含他们的头衔、名字、中间名和姓氏(如果已定义)以及邮寄地址。

我的代码似乎正在运行。

但是,在每个元组中,客户名称的整个而不是单个部分都需要用单引号引起来。地址周围还需要有引号。地址和全名需要用逗号隔开。

('Princess Elsa Frost', '33 Castle Street, London')

我的代码返回了正确的信息,但患者姓名的元素由逗号和单引号分隔


def process_clients(segment):

    #Creating a list to contain tuples with client full name and mailing address. 
    updated = []
    #Interacting through each dictionary, which represents each client
    for dic in segment:
        newclient=[]
    #Adding clients with a mailing address
        try:
            add = dic["address"]
        except:
            continue
    #Adding, in order, the "title", "first-name", "middle-name", "last-name" and "address" of each client
        for data in ["title", "first-name", "middle-name", "last-name", "address"]:
            try:
                value = dic[data]
                newclient.append(value)
    #If "title", "first-name", "middle-name" or "last-name" is not present in a clients data, no action is taken
            except:
                pass
    #Additing the tuples with extracted client data to the created list        
        updated.append(tuple(newclient))
    return updated


process_clients(segment)


[('Princess',' Elsa ',' Frost ', '33 Castle Street, London')]

【问题讨论】:

    标签: python-3.x list dictionary tuples extract


    【解决方案1】:

    看起来你想从:

    data = ('Princess', ' Elsa ', ' Frost ', '33 Castle Street, London')
    

    data = ('Princess Elsa Frost', '33 Castle Street, London')
    

    要去除' Elsa '' Frost ' 中多余的空格,您可以使用列表推导:

    data = [word.strip() for word in data]
    

    对于data 中的每个word,上面的行会去掉开头和结尾的空白,然后将其全部放入一个列表中。

    现在我们有了:

    data = ['Princess', 'Elsa', 'Frost', '33 Castle Street, London']
    

    要组合前三个元素,请使用.join()

    data = (' '.join(data[:-1]), data[-1])
    

    ' '.join(data[:-1]) 获取除最后一个之外的所有元素并将它们连接成一个字符串,其中每个元素由' ' 分隔。 data[-1] 是列表中的最后一个元素。

    所以现在是:

    data = ('Princess Elsa Frost', '33 Castle Street, London')
    

    【讨论】:

      猜你喜欢
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      相关资源
      最近更新 更多