使用另一个列表作为参考来分离和附加列表中的项目

Segregate and append items in list using another list as reference

我一直在努力弄清楚如何将一个列表中的项目附加到一个新列表中。列表中的数据实际上是来自ipconfig/all的信息。因为我想根据网络标题将项目分开,所以我将标题添加到另一个列表中以用作参考。这是我的代码:

listofstates = []
allconnections = []
leftconnections = []
mainlist = []
commands = "ipconfig/all"
pipe = Popen(commands, shell=True, stdout=PIPE)
for line in pipe.stdout:
    listofstates.append(line.strip())
for items in listofstates:
    splittedvalues = str(items).split(':')
    if "b''" not in splittedvalues:
        splittedvalues = [s for s in splittedvalues if s]
        element = [splittedvalues[0].replace("b'", "").replace(".", "")] + splittedvalues[1:]
        cleanedelement = (re.split(r'\s{2,}',str(element[0])) + element[1:])
        cleanedelement = [s for s in cleanedelement if s]
        allconnections.append(cleanedelement)
        leftvalues = str(splittedvalues[0])
        if "." not in leftvalues:
            wordcount = len(re.findall(r'\w+', leftvalues))
            if wordcount > 2:
                newvalues = leftvalues.replace("b'", "").replace("'", "")
                leftconnections.append(newvalues)

print (allconnections)
print (leftconnections) 

allconnections 的输出:

[["Windows IP Configuration'"], ['Host Name', " Bla Bla Bla'"], ['Primary Dns Suffix', " vitrox.local'"], ['Node Type', " Hybrid'"], ['IP Routing Enabled', " No'"], ['WINS Proxy Enabled', " No'"], ['DNS Suffix Search List', " black sheep'"], ['Ethernet adapter Ethernet', "'"], ['Media State', " Media disconnected'"], ['Connection-specific DNS Suffix', "'"], ['Description', " Intel(R) Ethernet Connection I-LM'"], ['Physical Address', " 00-B5-00-1E-F4-5G'"], ['DHCP Enabled', " Yes'"], ['Autoconfiguration Enabled', " Yes'"], ['Ethernet adapter Local Area Network 5', "'"], ['Connection-specific DNS Suffix', "'"], ['Description', " VirtualBox Host-Only Ethernet Adapter'"], ['Physical Address', " 0A-00-50-00-11-0B'"], ['DHCP Enabled', " No'"], ['Autoconfiguration Enabled', " Yes'"], ['Link-local IPv6 Address', ' fe69', 'aa2b', '4b5d', '2345', "5f07%08(Preferred)'"], ['IPv4 Address', " 10.0.0.05(Preferred)'"], ['Subnet Mask', " 255.255.255.0'"], ['Default Gateway', "'"], ['DHCPv6 IAID', " 539312188'"], ['DHCPv6 Client DUID', " 00-04-11-01-25-75-14-A4-54-B1-03-1E-F4-5E'"], ['DNS Servers', ' fec0', '0', '0', 'ffff', "1%1'"], ['fec0', '0', '0', 'ffff', "2%1'"], ['fec0', '0', '0', 'ffff', "3%1'"], ['NetBIOS over Tcpip', " Enabled'"]..............]

以上基本上是我从中提取数据的列表。

leftconnections 的输出:

['Windows IP Configuration', 'Ethernet adapter Ethernet', 'Ethernet adapter Local Area Network 5', 'Wireless LAN adapter Local Area Connection* 3', 'Wireless LAN adapter Local Area Connection* 12', 'Wireless LAN adapter Wi-Fi', 'Ethernet adapter Bluetooth Network Connection']

这是用作参考的列表

最终,我希望通过左连接中的标题分隔所有连接中的数据来获得这样的输出。

[[["Windows IP Configuration'"], ['Host Name', " Bla Bla Bla'"], ['Primary Dns Suffix', " vitrox.local'"], ['Node Type', " Hybrid'"], ['IP Routing Enabled', " No'"], ['WINS Proxy Enabled', " No'"], ['DNS Suffix Search List', " black sheep'"]],[['Ethernet adapter Ethernet', "'"], ['Media State', " Media disconnected'"], ['Connection-specific DNS Suffix', "'"], ['Description', " Intel(R) Ethernet Connection I-LM'"], ['Physical Address', " 00-B5-00-1E-F4-5G'"], ['DHCP Enabled', " Yes'"], ['Autoconfiguration Enabled', " Yes'"], ['Ethernet adapter Local Area Network 5', "'"], ['Connection-specific DNS Suffix', "'"], ['Description', " VirtualBox Host-Only Ethernet Adapter'"], ['Physical Address', " 0A-00-50-00-11-0B'"], ['DHCP Enabled', " No'"], ['Autoconfiguration Enabled', " Yes'"], ['Link-local IPv6 Address', ' fe69', 'aa2b', '4b5d', '2345', "5f07%08(Preferred)'"], ['IPv4 Address', " 10.0.0.05(Preferred)'"], ['Subnet Mask', " 255.255.255.0'"], ['Default Gateway', "'"], ['DHCPv6 IAID', " 539312188'"], ['DHCPv6 Client DUID', " 00-04-11-01-25-75-14-A4-54-B1-03-1E-F4-5E'"], ['DNS Servers', ' fec0', '0', '0', 'ffff', "1%1'"], ['fec0', '0', '0', 'ffff', "2%1'"], ['fec0', '0', '0', 'ffff', "3%1'"], ['NetBIOS over Tcpip', " Enabled'"]],[[...],[...],[...],[[...],[...]]]

我能想到的是制作这个 for 循环(不是工作代码):

for connection in leftconnections:
   if (*connection is the first*)
       mainlist.append(leftconnections) *until second connection is found*

代码的主要目的只是将ipconfig/all中的所有细节通过网络分开。所以,我实际上对其他方法持开放态度,因为我知道,我的代码现在有点乱。

非常感谢你愿意帮助我。

在您发布的代码中,您正在与 b' 纠缠不清,它位于 stdout 行的 表示 的开头.在您当前的代码中,stdoutbytes 的形式提供给您。要使它成为一个字符串,请调用它的 decode() 方法,或者通过使用 text=True 参数调用 Popen 从一开始就将其作为 str 获取。

The main purpose of the code is just to separate all the details in ipconfig/all by network. So, I'm actually open to other methods because I know, my code is a little messy right now.

我强烈建议使用 module/API 直接为您提供此信息,而不是从 ipconfig /all 的输出中收集信息。正如 wjandrea, try the wmic module Extracting Subnet Mask from my computer python.

中建议的那样

做不到这一点,试一试。我对另一个问题 中给出的代码进行了一些更改,以便它处理 ipconfig /all。请注意,它很脆弱。任何严重的事情都不要依赖它。

import subprocess

adapters = {}
current_adapter = None # Used to ignore the stuff between "Windows IP Configuration" and the first adapter
output = subprocess.check_output("ipconfig /all").decode()


for line in output.splitlines():
    # Determine if there's one of these type of adapters in the line
    for term in ["Ethernet adapter", "PPP adapter", 
                 "Tunnel adapter", "Wireless LAN adapter"]:
        if line.startswith(term) and ":" in line:
            adapter_name = line[len(term):-1]
            adapters[adapter_name] = {}
            current_adapter = adapters[adapter_name]
            break # Goes to the next line in the output
    else: # No break - the current line is not the start of a new adapter
        if current_adapter != None:
            split_at = " : "
            if split_at in line:
                # We assume this line contains a key/value pair
                key, value = line.split(split_at)
                key = key.replace(" .", "").strip()
                current_adapter[key] = value
                continue

            # At this point, the line is either a blank line, or an additional value
            value = line.strip()
            if value != "":
                # It's assumed to be an additional value
                # If it's the first additional value, make a list with the
                # original value, then append the value from this line
                if not isinstance(current_adapter[key], list):
                    current_adapter[key] = [current_adapter[key]]

                current_adapter[key].append(value)


for adapter_name, adapter in adapters.items():
    print(f"{adapter_name}:")
    for key, value in adapter.items():
        print(f'    "{key}" = "{value}"')
    print()

输出:

Ethernet:
    "Connection-specific DNS Suffix" = ""
    "Description" = "Realtek PCIe GBE Family Controller"
    "Physical Address." = "1C-1C-1C-1C-1C-1C"
    "DHCP Enabled." = "Yes"
    "Autoconfiguration Enabled" = "Yes"
    "Link-local IPv6 Address" = "fe80::fe80:fe80:fe80:fe80%8(Preferred)"
    "IPv4 Address." = "192.168.255.255(Preferred)"
    "Subnet Mask" = "255.255.255.0"
    "Lease Obtained." = "Wednesday, 10 October 2019 10:10:10 PM"
    "Lease Expires" = "Wednesday, 10 October 2019 10:10:10 PM"
    "Default Gateway" = "192.168.255.255"
    "DHCP Server" = "192.168.255.255"
    "DHCPv6 IAID" = "50505050"
    "DHCPv6 Client DUID." = "00-01-01-01-01-01-01-01-01-01-01-01-01-01"
    "DNS Servers" = "['192.168.255.255', '0.0.0.0']"
    "NetBIOS over Tcpip." = "Enabled"

VMware Network Adapter VMnet1:
    "Connection-specific DNS Suffix" = ""
    "Description" = "VMware Virtual Ethernet Adapter for VMnet1"
    "Physical Address." = "00-00-00-00-00-00"
    "DHCP Enabled." = "Yes"
    "Autoconfiguration Enabled" = "Yes"
    "Link-local IPv6 Address" = "fe80::fe80:fe80:fe80:fe8%19(Preferred)"
    "IPv4 Address." = "192.168.255.255(Preferred)"
    "Subnet Mask" = "255.255.255.255"
    "Lease Obtained." = "Wednesday, 10 October 2019 10:10:10 PM"
    "Lease Expires" = "Wednesday, 10 October 2019 10:10:10 PM"
    "Default Gateway" = ""
    "DHCP Server" = "192.168.255.255"
    "DHCPv6 IAID" = "484848480"
    "DHCPv6 Client DUID." = "00-01-00-01-01-01-01-01-01-01-01-01-01-01"
    "DNS Servers" = "['fec0:0:0:ffff::1%1', 'fec0:0:0:ffff::2%1', 'fec0:0:0:ffff::3%1']"
    "NetBIOS over Tcpip." = "Enabled"

VMware Network Adapter VMnet8:
    "Connection-specific DNS Suffix" = ""
    "Description" = "VMware Virtual Ethernet Adapter for VMnet8"
    "Physical Address." = "00-00-00-00-00-00"
    "DHCP Enabled." = "Yes"
    "Autoconfiguration Enabled" = "Yes"
    "Link-local IPv6 Address" = "fe80::fe80:fe80:fe80:fe8%10(Preferred)"
    "IPv4 Address." = "192.168.255.255(Preferred)"
    "Subnet Mask" = "255.255.255.255"
    "Lease Obtained." = "Wednesday, 10 October 2019 10:10:10 PM"
    "Lease Expires" = "Monday, 10 October 2019 10:10:10 PM"
    "Default Gateway" = ""
    "DHCP Server" = "192.168.255.255"
    "DHCPv6 IAID" = "484848480"
    "DHCPv6 Client DUID." = "00-01-00-01-01-01-01-01-01-01-01-01-01-01"
    "DNS Servers" = "['fec0:0:0:ffff::1%1', 'fec0:0:0:ffff::2%1', 'fec0:0:0:ffff::3%1']"
    "Primary WINS Server" = "192.168.255.255"
    "NetBIOS over Tcpip." = "Enabled"