具有可变成员的列表列表的产品

时间:2018-04-18 21:10:23

标签: python list membership

说我有这个输入数据

my_input_list = [[A],[A,B,C],[D],[D,E,F],[A,B,C,D,E,F],[A,C,E]]
items_that_appear_twice = [A,B,C]
items_that_appear_four = [D,E,F]

我想创建一个扩展,以便某些元素只允许出现两次。

my_output_list = [
[A],[A],
[A,B,C],[A,B,C],
[D],[D],[D],[D],
[D,E,F],[D,E,F],[D,E,F],[D,E,F],
[A,B,C,D,E,F],[A,B,C,D,E,F],[D,E,F],[D,E,F],
[A,C,E],[A,C,E],[E],[E]]

我厌倦了一些想法,并没有找到一个非常简洁的解决方案,比如从它们构建四个列表和list.remove()生成两个空列表。 例如,当我需要my_input_list[0]*4时,[A],[A],[],[]上的列表删除技术会提供[A],[A](两个空列表)。

3 个答案:

答案 0 :(得分:2)

我有一个工作版本:See Pyfiddle

my_input_list = [['A'],['A','B','C'],['D'],['D','E','F'],['A','B','C','D','E','F'],['A','C','E']]
items_that_appear_twice = ['A','B','C']
items_that_appear_four = ['D','E','F']

my_output_list = []
for my_input in my_input_list:
    items_allowed_to_appear_twice = list(filter(
        lambda value: (value in items_that_appear_twice 
                       or value in items_that_appear_four),
        my_input))

    items_allowed_to_appear_four = list(filter(
        lambda value: value in items_that_appear_four,
        my_input))

    my_output_list += 2*[items_allowed_to_appear_twice]
    if len(items_allowed_to_appear_four):
        my_output_list += 2*[items_allowed_to_appear_four]

print(my_output_list)

答案 1 :(得分:1)

static void stopWriter()
{

    Process[] proc = Process.GetProcessesByName("staticEngineWriter");

    foreach (System.Diagnostics.Process CurrentProcess in proc)
    {
        Console.Writeline(CurrentProcess.MainWindowTitle); //debug

        if (CurrentProcess.MainWindowTitle.Contains("My Writer"))
        {
            CurrentProcess.Kill();
        }
    }

}

答案 2 :(得分:1)

下面是我的解决方案,首先对子列表进行排序,然后根据不同的情况追加到结果中。

my_input_list = [['A'],['A','B','C'],['D'],['D','E','F'],['A','B','C','D','E','F'],['A','C','E']]
items_that_appear_twice = ['A','B','C']
items_that_appear_four = ['D','E','F']

result = []
for sublist in my_input_list:
    appearence = {1:[], 2:[], 4:[]}
    for item in sublist:
        appearence[2].append(item) if item in items_that_appear_twice else (appearence[4].append(item) if item in items_that_appear_four else appearence[1].append(item))
    if len(appearence[2]) > 0:
        result.append([appearence[2] + appearence[4]] * 2 + ([appearence[4]] * 2 if appearence[4] and len(appearence[4]) > 0 else []))
    else:
        result.append([appearence[4]] * 4)
for item in result:
    print(item)

输出:

[['A'], ['A']]
[['A', 'B', 'C'], ['A', 'B', 'C']]
[['D'], ['D'], ['D'], ['D']]
[['D', 'E', 'F'], ['D', 'E', 'F'], ['D', 'E', 'F'], ['D', 'E', 'F']]
[['A', 'B', 'C', 'D', 'E', 'F'], ['A', 'B', 'C', 'D', 'E', 'F'], ['D', 'E', 'F'], ['D', 'E', 'F']]
[['A', 'C', 'E'], ['A', 'C', 'E'], ['E'], ['E']]
[Finished in 0.178s]