简体   繁体   English

如何将元素列表转换为0或1的列表

[英]How to convert a list of elements into a list with 0 or 1

I have a list whose elements are either a json object or None. 我有一个列表,其元素是json对象或None。 What would be the most elegant way to convert it into a list of 0's and 1's. 将其转换为0和1的列表的最优雅的方法是什么。 For example here is my input : 例如,这是我的输入:

mylist = [j1, j2, None, j3, None]

j1, j2, j3 are json objects. j1,j2,j3是json对象。 The expected output is 预期的输出是

output_list = [1, 1, 0, 1, 0]

I can implement this using a for loop followed by if statement. 我可以使用for循环和if语句来实现此目的。 Is there a way to do it which is more elegant/pythonic? 有没有办法做到这点呢?

You can use a list comprehension and a conditional expression : 您可以使用列表推导条件表达式

mylist[:] = [0 if x is None else 1 for x in mylist]

See a demonstration below: 请参见下面的演示:

>>> mylist = ['a', 'b', None, 'c', None]
>>> mylist[:] = [0 if x is None else 1 for x in mylist]
>>> mylist
[1, 1, 0, 1, 0]
>>>

The [:] will make it so that the list object is kept the same: [:]将使列表对象保持相同:

>>> mylist = ['a', 'b', None, 'c', None]
>>> id(mylist)
34321512
>>> mylist[:] = [0 if x is None else 1 for x in mylist]
>>> id(mylist)
34321512
>>>

You can also use map function on your list, here's a python shell's session: 您还可以在列表上使用map函数,这是python shell的会话:

>>> l = ['j1', 'j2', None, 'j3', None]
>>> map(lambda e : e is None, l)
[False, False, True, False, True]
>>> map(lambda e : e is not None, l)
[True, True, False, True, False]
>>> map(lambda e : int(e is not None), l)
[1, 1, 0, 1, 0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM