合并列表的某些元素

时间:2016-05-03 16:47:45

标签: python

我有这个字符串列表:

Mylist =  ['ASA', 'TD', 'UDP', '255.255.255.255', '/80', 'to', '255.255.255', '/88']

如何将此作为最终结果:

Mylist = ['ASA', 'TD', 'UDP', '255.255.255.255/80', 'to', '255.255.255/88']

4 个答案:

答案 0 :(得分:1)

快速forif声明:

def merge_port(input_list):
    output_list = []
    for i,item in enumerate(input_list):
        if item.startswith('/'):
             output_list[-1] += item
        else:
            output_list.append(item)
    return output_list

这只是一个快速的工作,我没有测试,但应该给你的想法。您还可以添加错误测试,如果您在列表的开头遇到了/...的列表,则会出现异常。

答案 1 :(得分:0)

我找到了答案谢谢Evert

for line in Mylist:
     newline = line[:3] + [line[3] + line[4], line[5], line[6] + line[7]] 
     print (newline)

Mylist = ['ASA', 'TD', 'UDP', '255.255.255.255/80', 'to', '255.255.255/88']

谢谢大家!

答案 2 :(得分:-1)

我决定对你的问题有一些乐趣并介绍正则表达式的概念。 Python通过包re处理此问题(因此import re)。这样我们就可以将该列表中的项目与IP地址模式进行匹配,并检查其后面的项目是否与您给出的格式的端口号相对应。

如果您有任何疑问,请与我们联系:

from __future__ import print_function
import re

some_list = ['ASA', 'TD', 'UDP', '255.255.255.255', '/80', 'to', '255.255.255.255', '/88']
new_list = []

count = 0
ip_pattern = re.compile('^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$')
port_pattern = re.compile('/[0-9]*')

for i in some_list:
    count += 1
    if ip_pattern.match(i):
        try:
            next_item = some_list[count]

            if port_pattern.match(next_item):
                new_item = ''.join([i, next_item])
            else:
                new_item = i

            new_list.append(new_item)
        except IndexError:
            new_list.append(i)
    elif port_pattern.match(i):
        pass  # Don't add to the new list
    else:
        new_list.append(i)

print('Original List: {0}'.format(some_list))
print('New List: {0}'.format(new_list))
print('Formatted string: {0}'.format('\t'.join(new_list)))

输出:

Original List: ['ASA', 'TD', 'UDP', '255.255.255.255', '/80', 'to', '255.255.255.255', '/88']
New List: ['ASA', 'TD', 'UDP', '255.255.255.255/80', 'to', '255.255.255.255/88']
Formatted string: ASA   TD  UDP 255.255.255.255/80  to  255.255.255.255/88

答案 3 :(得分:-2)

这很简单,因为python简直太棒了^^

output = input[:]  # Although I wouldn't call the input value input, because it shadows the builtin function
output[3:5] = [output[3] + output[4]]  # this makes the list shorter to fit the new list in
output[5:7] = [output[5] + output[6]]  # because the list is one shorter, the indices are one less each