列表的Python Django Lambda表达式

时间:2018-09-27 20:25:22

标签: python

我需要在Python中更新一个列表,

data = [{' Customers ','null,blank '},{' CustomersName ','max=50,null,blank '},{' CustomersAddress ','max=150,blank '},{' CustomersActive ','Active '}]

我想编写一个Lambda表达式以在列表中存储客户,CustomersName,并删除空白。 我绝对是Python新手,没有任何知识!

2 个答案:

答案 0 :(得分:1)

正如我所看到的,您已经在列表中声明了字典,但是Dict是错误的,它应该是{“ key”:“ value”},所以我认为您需要这样将其更改为List:

  data = [[' Customers ','null,blank '],[' CustomersName ','max=50,null,blank '],[' CustomersAddress ','max=150,blank '],[' CustomersActive ','Active ']]

然后,以下内容将使您获得您的期望!

data_NameExtracted = [x[0].strip() for x in data]

答案 1 :(得分:0)

您不能将其放在lambda表达式中,但可以使用如下生成器对象:

# please note that i have used tuples instead of sets, 
# because sets are unordered
data = [
    (' Customers ','null,blank '),
    (' CustomersName ','max=50,null,blank '), 
    (' CustomersAddress ','max=150,blank '),
    (' CustomersActive ','Active ')
]

# Indexing is not allowed for set objects
values = [item[0].strip() for item in data]

请参阅:

https://wiki.python.org/moin/Generators

https://docs.python.org/3/tutorial/datastructures.html#sets

编辑:

如果您不想使用字典,则可以使用以下内容:

data = [
    {' Customers ': 'null,blank '},
    {' CustomersName ': 'max=50,null,blank '}, 
    {' CustomersAddress ': 'max=150,blank '},
    {' CustomersActive ': 'Active '}
]
# expecting a single value in the dicts
values = [item.values()[0].strip() for item in data]