gpt4 book ai didi

python - 如何分隔列表中的逗号分隔值以使其成为列表的单独值

转载 作者:太空宇宙 更新时间:2023-11-04 11:15:42 25 4
gpt4 key购买 nike

我正在 python 中的列表中获取一些开关命令输出,我能够在列表中获得结果,但是该列表包含两个元素,甚至这些元素是逗号分隔的,我想将这些逗号分隔值作为单个元素列表。

我正在使用 netmiko 模块,我正在使用 python 取出列表中的一些命令输出。

                for k in range(len(cli_commands)):
net_connect.send_command(cli_commands[k])
vall=net_connect.send_command(cli_commands[k])
myList1.append(vall)
```print(myList)

Actual result is:

['Cisco IOS Software, C2960S Software (C2960S-UNIVERSALK9-M), Version 15.0(2)SE11, RELEASE SOFTWARE (fc3)', 'NAME: "1", DESCR: "WS-C2960S-24TS-L"\nPID: WS-C2960S-24TS-L , VID: V02 , SN: FOC1452X5C5\n\n']


Expectation:

['Cisco IOS Software', 'C2960S Software (C2960S-UNIVERSALK9-M)', 'Version 15.0(2)SE11', 'RELEASE SOFTWARE (fc3)', 'NAME: "1"', 'DESCR: "WS-C2960S-24TS-L"\nPID: WS-C2960S-24TS-L' ,' VID: V02' , 'SN: FOC1452X5C5\n\n']

or
['Cisco IOS Software','C2960S Software (C2960S-UNIVERSALK9-M)',Version 15.0(2)SE11','DESCR: "WS-C2960S-24TS-L"\nPID: WS-C2960S-24TS-L','SN: FOC1452X5C5\n\n']

最佳答案

您将必须.split(',') 每个字符串以获得嵌套列表,然后使其简单明了。 .split() 的使用删除了每个 sub_string 开头和结尾的额外空格。

the_list = ['Cisco IOS Software, C2960S Software (C2960S-UNIVERSALK9-M), Version 15.0(2)SE11, RELEASE SOFTWARE (fc3)', 'NAME: "1", DESCR: "WS-C2960S-24TS-L"\nPID: WS-C2960S-24TS-L  , VID: V02  , SN: FOC1452X5C5\n\n']

the_list = [map(lambda x: x.strip(), item.split(',')) for item in the_list]
new_list = [item for sub_list in the_list for item in sub_list]

第一行将 the_list 中的每个字符串转换为映射生成器,该映射生成器在除以 ' 之后将 .strip()(修剪空格)应用于每个子字符串,' 字符。第二个只是为了让列表变得简单,这是 [[1, 2], [3, 4]] 将变成 [1, 2, 3, 4]。它相当于:

the_list = ['Cisco IOS Software, C2960S Software (C2960S-UNIVERSALK9-M), Version 15.0(2)SE11, RELEASE SOFTWARE (fc3)', 'NAME: "1", DESCR: "WS-C2960S-24TS-L"\nPID: WS-C2960S-24TS-L  , VID: V02  , SN: FOC1452X5C5\n\n']

new_list = []
for string in the_list:
for item in string.split(','):
new_list.append(item.strip())

关于python - 如何分隔列表中的逗号分隔值以使其成为列表的单独值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57051330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com