如何使用python将给定的“键-值”列表拆分为两个列表,分别为“键”和“值”

btqmn9zl  于 2023-01-03  发布在  Python
关注(0)|答案(4)|浏览(169)

这是我的列表

List = ['function = function1', 'string = string1', 'hello = hello1', 'new = new1', 'test = test1']

我需要将列表分为两个不同的列表,分别为“键”和“值”

List = ['function = function1', 'string = string1', 'hello = hello1', 'new = new1', 'test = test1']

密钥列表

KeyList = ['function', 'string', 'hello', 'new', 'test']

值列表

ValueList = ['function1', 'string1', 'hello1', 'new1', 'test1']
txu3uszq

txu3uszq1#

有不同的可能的方法。一个是蒂姆提出的方法,但如果你不熟悉你也可以这样做:

List = ['function = function1', 'string = string1', 'hello = hello1', 'new = new1', 'test = test1']

KeyList = []
ValueList = []
for item in List:
    val = item.split(' = ')
    KeyList.append(val[0])
    ValueList.append(val[1])
    
print(KeyList)
print(ValueList)

输出为:

['function', 'string', 'hello', 'new', 'test']
['function1', 'string1', 'hello1', 'new1', 'test1']
xhv8bpkk

xhv8bpkk2#

您可以简单地使用split(" = ")并将键值对列表解压缩为两个元组:

keys, values = zip(*map(lambda s: s.split(" = "), List))

# keys
# >>> ('function', 'string', 'hello', 'new', 'test')
# values
# >>>('function1', 'string1', 'hello1', 'new1', 'test1')

这是基于zip(*a_zipped_iterable)作为解压缩函数工作的事实。

fjnneemd

fjnneemd3#

我们可以在这里使用re.findall

inp = ['function = function1', 'string = string1', 'hello = hello1', 'new = new1', 'test = test1']
keys = [re.findall(r'(\w+) =', x)[0] for x in inp]
vals = [re.findall(r'\w+ = (\w+)', x)[0] for x in inp]
kqlmhetl

kqlmhetl4#

keys = [pair[0] for pair in pairs]
values = [pair[1] for pair in pairs]

相关问题