[英]split list into n chunks according \n in python
I have a list like:我有一个类似的列表:
prices=['deposit:2000$ \n monthly:500$','deposit:3500$ \n monthly:800$','deposit:2800$ \n monthly:670$',...]
I want to divide this list into deposit sub list and monthly sub list.我想将此列表分为存款子列表和每月子列表。 I just need to split this according \n (new line).
我只需要根据 \n (新行)拆分它。 like:
喜欢:
deposit=[deposit:2000$,deposit:3000$,deposit:2800$,....]
monthly=[monthly:500$,monthly:800$,monthly:670$,...]
but I don't know how I can fix it.但我不知道如何解决它。
You can use list comprehension twice,您可以使用两次列表推导,
prices=['deposit:2000$ \n monthly:500$','deposit:3500$ \n monthly:800$','deposit:2800$ \n monthly:670$']
deposit = [item.split("\n")[0].strip() for item in prices]
monthly = [item.split("\n")[1].strip() for item in prices]
You can also do this in one step using zip,您也可以使用 zip 一步完成此操作,
deposits, monthly = zip(*[item.split("\n ") for item in prices])
Note that the returned deposits and monthly will be tuple.请注意,退回的存款和每月将是元组。 You can cast it to list if needed.
如果需要,您可以将其投射到列表中。
something like the below类似于下面的东西
prices = ['deposit:2000$ \n monthly:500$', 'deposit:3500$ \n monthly:800$', 'deposit:2800$ \n monthly:670$']
deposit = []
monthly = []
for p in prices:
d, m = p.split('\n')
deposit.append(d)
monthly.append(m)
print(f'{monthly} {deposit}')
output output
[' monthly:500$', ' monthly:800$', ' monthly:670$'] ['deposit:2000$ ', 'deposit:3500$ ', 'deposit:2800$ ']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.