根据特定索引处的嵌套列表中的元素筛选列表

时间:2017-04-22 08:46:31

标签: python list python-3.x

我有一个包含以下列表的列表:

[['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]

我希望通过引用列表列表中每个列表的第三部分中的字母表来获取列表列表中的值。

示例,我希望python为列表列表中的每个项目打印由字母“G”表示的元素

output = [4.2,3.4]
         [8.7,5.4]

这是我尝试过的:

L = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
newList = []

for line in L:
    if line[0][2] == 'G'
        newList.append([float(i) for i in line[0:2]])
print(newList)

我的错误将在第5行,因为我不确定我是否能够这样做。问候。

7 个答案:

答案 0 :(得分:3)

简单列表理解:

L = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
newList = [l[0:2] for l in L if l[2] == 'G']

print(newList)

输出:

[['4.2', '3.4'], ['8.7', '5.4']]

答案 1 :(得分:2)

我建议使用collections.defaultdict作为多值字典:

from collections import defaultdict
d = defaultdict(list)
for x in L:
    d[x[2]].append(x[:2])

现在,您可以使用d['G']获取所需内容,还可以使用d['H']获取'H'的结果!

修改:来源append multiple values for one key in Python dictionary

答案 2 :(得分:1)

您的代码中有2个问题,

1. line = ['4.2', '3.4', 'G'] for 1st iteration
hence to check for 'G', look out for line[2] == 'G' instead of line[0][3] == 'G'
2. use 'G' instead off 'house'.

>>> for line in L:
...   if line[2] == 'G':
...     newList.append([float(i) for i in line[0:2]])
... 
>>> newList
[[4.2, 3.4], [8.7, 5.4]]

答案 3 :(得分:0)

你可以通过迭代列表列表来使用字典。

lst = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
dict1 = {}

for l in lst:
    if l[2] in dict1.keys():
        dict1[l[2]].append(l[0:2])
    else:
        dict1[l[2]] = [l[0:2]]
        print l[0:2]

print dict1['G']

答案 4 :(得分:0)

您可以使用列表理解表达式以及map的用法创建一个基于元素返回子列表的函数:

def get_element_by_alpha(alpha, data_list):
    #        v map returns generator object in Python 3.x,hence type-cast to `list`
    return [list(map(float, s[:2])) for s in data_list if s[2]==alpha]
    #                 ^ type-cast the number string to `float` type 

示例运行:

>>> my_list = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]

>>> get_element_by_alpha('G', my_list)
[[4.2, 3.4], [8.7, 5.4]]

>>> get_element_by_alpha('H', my_list)
[[2.4, 1.2]]

>>> get_element_by_alpha('A', my_list)  # 'A' not in the list
[]

答案 5 :(得分:0)

列表理解将执行此操作:

private static void Test()
{
    dynamic parameters = new ExpandoObject();
    parameters.test= "myImage";
    parameters.arg2= 2;

    var results = RunPowerShellFunction("My-Function", parameters);
    var obj = results[0];
    var str = results[1];
}

private static dynamic RunPowerShellFunction(string functionName, dynamic parameters)
{
    dynamic rv = null;

    try
    {
        InitialSessionState iss = InitialSessionState.CreateDefault();

        using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))
        {
            runspace.Name = typeof(DockerManager).Name;
            runspace.Open();

            RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
            runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

            using (var mainPowerShell = System.Management.Automation.PowerShell.Create())
            {
                mainPowerShell.Runspace = runspace;

                mainPowerShell.AddScript(LoadedScriptText, false);
                mainPowerShell.Invoke();

                var cmd = mainPowerShell.AddCommand(functionName);

                if (parameters != null)
                {
                    foreach (var parameter in parameters)
                    {
                        cmd.AddParameter(parameter.Key, parameter.Value);
                    }
                }

                rv = cmd.Invoke();
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }

    return rv;
}

答案 6 :(得分:0)

@Electric您编辑的代码。

L = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
newList = []

# line = ['4.2','3.4','G']
for line in L:
    if line[2] == 'G': # ':' was missing.
        newList.append(line[:2]) # line[:2] => ['4.2','3.4']
print(newList)