简体   繁体   English

Python扩展列表理解

[英]Python Extend List Comprehension

I'm trying to make a list comprehension while parsing multiple arguments, which can be single, comma seperated or null values. 我正在尝试在解析多个参数时使列表理解,这些参数可以是单个,逗号分隔或空值。

The following is a short working piece of code: 以下是一段简短的代码:

csv_ip = '192.168.1.1,192.168.1.20'
single_ip = '33.44.33.22'
empty_ip = None

ip_list = [ip for ip in [csv_ip.split(','), single_ip, empty_ip] if ip]
print ip_list
>> [['192.168.1.1', '192.168.1.20'], '33.44.33.22']

I'm wondering if I can extend the list when I split the CSV values, so that the list will be as following: 我想知道在拆分CSV值时是否可以扩展列表,因此列表如下:

['192.168.1.1', '192.168.1.20', '33.44.33.22']

Is it possible to extend a list comprehension with another list ? 是否可以扩展列表理解与另一个列表?

You can just create a single flat list before filtering by "adding" sub-lists: 您可以在通过“添加”子列表进行过滤之前只创建一个平面列表:

csv_ip = '192.168.1.1,192.168.1.20'
single_ip = '33.44.33.22'
empty_ip = None

ip_list = [ip for ip in csv_ip.split(',') + [single_ip] + [empty_ip] if ip]
print ip_list
>>> ['192.168.1.1', '192.168.1.20', '33.44.33.22']

If you want a version that treats all of the argument cases identically, you can use: 如果要使用一个版本来平等对待所有参数情况,则可以使用:

ip_list = [ip for s in [csv_ip, single_ip, empty_ip] for ip in (s.split(",") if s else [])]

There's no way to do an actual extend , but you can achieve the same result by using itertools.chain 没有办法进行实际的extend ,但是您可以通过使用itertools.chain获得相同的结果。

from itertools import chain

ip_list = [ip for ip in chain(csv_ip.split(','), [single_ip, empty_ip]) if ip]

itertools.chain takes in a bunch of iterables, and then iterates over all the elements of the first, then the second, and so on, so you need to send in single_ip and empty_ip in a list as well. itertools.chain吸收了一堆可迭代对象,然后迭代第一个元素,然后第二个元素的所有元素,依此类推,因此您还需要在列表中发送single_ipempty_ip

Since the whole point is that you don't know which arguments will contain comma-separated IPs, which will contain a single IP, and which will contain None , you won't get far if you try to hard-code their behavior. 既然要说的是,您不知道哪些参数将包含逗号分隔的IP,哪些将包含单个IP,哪些将包含None ,那么如果您尝试对它们的行为进行硬编码,您将不会走得很远。 Instead, check each argument and process it appropriately: 相反,请检查每个参数并进行适当处理:

csv_ip = '192.168.1.1,192.168.1.20'
single_ip = '33.44.33.22'
empty_ip = None
args = csv_ip, single_ip, empty_ip
result = [item for arg in args for item in (arg.split(',') if arg else '')]

Result: 结果:

>>> for item in result:
...     print(item)
...
192.168.1.1
192.168.1.20
33.44.33.22

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

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