简体   繁体   English

字符串化列表分为两个单独的列表

[英]stringified list to two separate lists

I have a stringified list that looks something like this: 我有一个字符串列表,看起来像这样:

'[a:1,b:1,c:2,a:3]'

I want to separate this into two lists. 我想将其分为两个列表。

['a','b','c','d'] and [1,1,2,3] ['a','b','c','d'][1,1,2,3]

is there any pythonic way of doing this without using eval (it doesnt work anyways)? 是否有任何不使用eval的方式来执行此操作的Python方法(反正还是不起作用)?

You can use re.findall() to find the characters and numbers and zip function to separate them : 您可以使用re.findall()查找字符和数字,并使用zip函数将它们分开:

>>> a='[a:1,b:1,c:2,a:3]'

>>> import re
>>> zip(*re.findall(r'([a-z]):(\d)',a))
[('a', 'b', 'c', 'a'), ('1', '1', '2', '3')]
import re
zip(*re.findall(r'([a-z]):([0-9])', my_string))

Depending your use, you can also add some + : 根据您的用途,您还可以添加一些+

>>> zip(*re.findall(r'([a-z]+):([0-9]+)', '[a:1,blabla:1,c:20,a:3]'))
[('a', 'blabla', 'c', 'a'), ('1', '1', '20', '3')]

Just to go a little bit further in the requirement to get a list of ints: 为了更进一步了解整数列表,您需要:

str = '[a:1,b:1,c:2,a:3]'
p,q = zip(*[(x,int(y)) for x,y in re.findall('([a-z]+):(\d+)', str)])

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

相关问题 从“列表”和“列表列表”中创建两个单独的“列表列表” - Creating two separate “lists of lists” out of “list” & “list of lists” 在两个单独的列表上使用相同的列表推导 - Using identical list comprehensions on two separate lists 如何将python列表上的每月和每天的文件名分成两个单独的列表? - How to separate monthly and daily filenames on python list into two separate lists? 将字符串化列表的列表转换为数据框,同时保持索引 - Convert a list of stringified lists into a dataframe whilst maintaining index 根据逗号将字符串列表拆分为两个单独的列表 - Split list of strings into two separate lists based on comma 用一行代码从两个单独的列表生成一个新列表 - Generating a new List from two Separate Lists with one Line of Code Python-如何将列表动态拆分为两个单独的列表 - Python - How to split a list into two separate lists dynamically 如何将一个列表分为两个不同的列表?(Python2.7) - How to separate a list into two different lists ?(Python2.7) 根据元素的某些方面,如何将Python列表分成两个列表 - How to separate a Python list into two lists, according to some aspect of the elements 将元组列表中的元素排序为两个单独的列表 - Sorting elements from a list of tuples into two separate lists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM