简体   繁体   English

遍历列表

[英]Iterating Over A List

I have a function that I'd like to iterate over a list of lists.我有一个 function ,我想遍历一个列表。 The thing is, this list of lists is dynamic, meaning it changes based on user input.问题是,这个列表列表是动态的,这意味着它会根据用户输入而变化。

Here is an example of my code:这是我的代码示例:

result = func(5)
for z in Z[0]:
    result += func(z)

where Z is the dynamic lists of lists and func is my function.其中 Z 是列表的动态列表,func 是我的 function。 The function should iterate over every element in the list subsetted list Z[0] and sum the results. function 应该遍历列表子集列表 Z[0] 中的每个元素并对结果求和。 The code works when the list of lists looks like this:当列表列表如下所示时,该代码有效:

Z = [[1.1],[2.1],[3.1],[4.1]]

were Z[0] is just [1.1]. Z[0] 只是 [1.1]。 However sometimes this dynamic list of lists has more elements in each list, in which case i need to iterate over each element.然而,有时这个动态列表在每个列表中都有更多元素,在这种情况下,我需要遍历每个元素。 Like below:如下所示:

Z = [list([1.1, 1.3]),list([3.1]),list([4]])

in which case:在这种情况下:

Z[0] = [list([1.1, 1.3])]

and my code should do the following:我的代码应该执行以下操作:

result = func(5)
for z in Z[0]:
    result += func(z)

....
func(1.1) + func(1.3)

When I try to run the code with the list of lists I get an error: "can only concatenate list (not "float") to list"当我尝试使用列表列表运行代码时,出现错误:“只能将列表(而不是“浮动”)连接到列表”

I'm sure it has something to do with trying to iterate over a list.我确信这与尝试迭代列表有关。 If anyone has an easy fix to this, or knows the issue i'd love to know.如果有人对此有简单的解决方法,或者知道我很想知道的问题。

EDIT: I suppose my real issue is how these dynamic lists are being formed as pointed out by the answers below, I'll try to explain my issue a little further:编辑:我想我真正的问题是这些动态列表是如何形成的,正如下面的答案所指出的,我将尝试进一步解释我的问题:

I'm using an answer here given by @Michael: Replacing certain elements of an array based on a given index我在这里使用@Michael 给出的答案: 根据给定索引替换数组的某些元素

here is the code i use to produce the list of lists:这是我用来生成列表列表的代码:

Arr1 = [9,7,3,1]

Arr2 = [[14,6],[13,2]]

Arr3 = [0,2]

Z = np.array([[Arr1[i]] if not np.sum(Arr3 == i) else Arr2[i] for i in np.arange(Arr1.size)], dtype=object)

Z = [[list([14, 6])], [list([7])], list[([13, 2])], list[([1])]]

Subsetting Z[0] results with子集 Z[0] 结果与

[list([14,6])]

which then gives me the error (can only concatenate list (not "float") to list) when i try to iterate.当我尝试迭代时,这给了我错误(只能将列表(而不是“浮动”)连接到列表中)。

When the condition i = Arr3 is not met (say Arr3 was empty) and it just reverts to the original array the output of this code gives:当条件 i = Arr3 不满足(比如 Arr3 为空)并且它只是恢复到原始数组时,此代码的 output 给出:

Z = [[9][7][3][1]]

Z[0] = [9]

And with that the code to iterate over the list works.这样,迭代列表的代码就可以工作了。 However I need to work for above as well.但是我也需要为上述工作。

IF I remove brackets from this line of code here:如果我从这行代码中删除括号:

Z = np.array([[Arr1[i]] if not np.sum(Arr3 == i) else Arr2[i] for i in np.arange(Arr1.size)], dtype=object) 

remove brackets around [Arr1[i]]
--->

Z = np.array([Arr1[i] if not np.sum(Arr3 == i) else Arr2[i] for i in np.arange(Arr1.size)], dtype=object)

Then然后

Z = [list([14,6]),list([7]),list([13,2]),list([1])]

and
z[0] = [14,6]

and the code to iterate over the list works, But, then it does not work for the situation when the condition i = Arr 3 is not met, because the output looks like并且迭代列表的代码有效,但是,它不适用于不满足条件 i = Arr 3 的情况,因为 output 看起来像

[9 7 3 1]

Z[0] = 9

and I get the error 'float' object is not iterable.我得到错误'float' object is not iterable。

Sorry that is a lot, but I think it explains my issue better.抱歉,这很多,但我认为它更好地解释了我的问题。 I'm unsure out to get the list formation correct for any situation.我不确定是否在任何情况下都能正确生成列表。

its hard to kind of make sense of your question, but if you are just trying to sum each list of nums inside the main list then you can do something like很难理解您的问题,但是如果您只是想对主列表中的每个 nums 列表求和,那么您可以执行类似的操作

def sum_nums(nums: list):
    return [sum(num) for num in nums]


nums = [
    [1, 2],
    [7, 9, 10],
    [2],
    [9]
]

print(sum_nums(nums))

OUTPUT OUTPUT

[3, 26, 2, 9]

If every element of Z is a list, just with differing sizes (ie [1.1] , or [1.1, 2.2] , etc.) You can iterate over the list and the size of the list will not matter.如果Z的每个元素都是一个列表,只是大小不同(即[1.1][1.1, 2.2]等),您可以遍历列表,列表的大小无关紧要。

for l in Z:
    result = 0

    for z in l:
        result += func(z)

    # do something with inner list result

For each list in Z, [1.1] is a list, and then for each element in the lists in Z, if above then 1.1 , run func on this value and then add to result.对于 Z 中的每个列表, [1.1]是一个列表,然后对于 Z 中列表中的每个元素,如果高于1.1 ,则在此值上运行 func 然后添加到结果。

If Z can be a list of elements that are not a list, (ie Z = [1.1, 2.2] ) then this method will not work, but you have not shown this to be your case.如果 Z 可以是不是列表的元素列表(即Z = [1.1, 2.2] ),那么此方法将不起作用,但您没有证明这是您的情况。

EDIT - added in result to list to get sums of inner lists individually编辑 - 将结果添加到列表中以单独获取内部列表的总和

Your input is:您的输入是:

Z = [[1.1, 1.3],[2.1],[3.1],[4.1]]

I think what you need to do is iterate over all elements, apply your function and add the results and return我认为您需要做的是遍历所有元素,应用您的 function 并添加结果并返回

def sum_of_all_elements(list_of_list):
   result = 0
   for nested_list in list_of_list:
      for element in nested_list:
         result += func(element)
   return result
print(sum_of_all_elements(Z))

Using line comprehension使用行理解

result = sum([ func(element) for element in nested_list for nested_list in Z])

Your logic looks correct.你的逻辑看起来是正确的。 I tested it on both examples you provided with the code below, and it produces the correct results.我在您使用下面的代码提供的两个示例上对其进行了测试,它产生了正确的结果。

def func(x):
    return x**2

Z1 = [[1.1],[2.1],[3.1],[4.1]] # works
Z2 = [list([1.1, 1.3]), list([3.1]), list([4])] # works
 
result1 = func(5)
for z in Z1[0]:
    result1 += func(z)
print(result1)
## Result is 26.21
# (5**2) + (1.1**2) = 25 + 1.21 = 26.21

result2 = func(5)
for z in Z2[0]:
    result2 += func(z)
print(result2)
## Result is 26.21
# (5**2) + (1.1**2) + (1.3**2) = 25 + 1.21 + 1.69 = 27.9

However, I believe your issue arises when the input array Z has more layers of nested lists than is expected.但是,我相信当输入数组 Z 的嵌套列表层数超出预期时,就会出现您的问题。 In the example below, the value "1" is formatted as a separate list.在下面的示例中,值“1”被格式化为单独的列表。 When the code iterates over 1.1 and 1.3, it can handle both of these cases because they are floats.当代码迭代 1.1 和 1.3 时,它可以处理这两种情况,因为它们是浮点数。 Once the code gets to the third element which is formatted as a list [1], it is "surprised" and does not know how to handle the list because it was expecting a float.一旦代码到达格式化为列表 [1] 的第三个元素,它就会“惊讶”并且不知道如何处理该列表,因为它期待一个浮点数。 The code was not designed to expect this new extra list layer.代码的设计初衷不是为了期待这个新的额外列表层。

Z3 = [list([1.1, 1.3, [1]]), list([3.1]), list([4])] # does not work

result3 = func(5)
for z in Z3[0]:
    result3 += func(z) ## Error occurs on this line
print(result3)

To avoid this issue, you could make sure the user does not input more nested lists than is expected by your code.为避免此问题,您可以确保用户输入的嵌套列表不超过您的代码预期的数量。 Alternatively, instead of using nested lists, you could use numpy arrays or pandas dataframes and add a new dimension instead of a new level of a nested list.或者,您可以使用 numpy arrays 或 pandas 数据框,而不是使用嵌套列表,并添加新维度而不是新级别的嵌套列表。

numbers = [1, 2, 3, 4, 5, 6]
new_number = [n + 1 for n in range (1, 10)]
name = "AKHIL  CHOWDARY"
new_name = [letter for letter in name if letter! = " "]
print(new_number, new_name)
new_number = [n + n for n in range(15) if n % 2   != 0]
print(new_number)
names = ["akhil", "mahesh", "suresh", "rajesh", "dinesh"]
new_names = [name for name in names if len(name) > 5]
print(new_names)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM