简体   繁体   中英

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:

['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

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.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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