我正在python的list内获取一些switch命令输出,我能够在list中获取结果,但是该list包含两个元素,即使那些元素也是逗号分隔的,我也想获取那些逗号分隔的值作为的单个元素列表。
我正在使用netmiko模块,其中我使用python在列表中取出一些命令输出。
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
答案 0 :(得分:1)
好像您需要str.split
和list.extend
例如:
myList1 = []
for k in range(len(cli_commands)):
net_connect.send_command(cli_commands[k])
vall=net_connect.send_command(cli_commands[k])
myList1.extend(vall.strip().split(","))
print(myList1)
答案 1 :(得分:1)
您将必须.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())
答案 2 :(得分:1)
绝对毁灭的答案是正确的,但您必须像这样使用它
myList = ['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']
cs_mylist = []
for y in [x.split(',') for x in myList]:
for z in y:
cs_mylist.append(z)
print(cs_mylist)