简体   繁体   English

迭代Python中的列表列表

[英]Iterating over lists of lists in Python

I have a list of lists: 我有一份清单清单:

lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]

I want to iterate over each element and perform some string operations on them for example: 我想迭代每个元素并对它们执行一些字符串操作,例如:

replace("(", "")

I tried iterating over the list using: 我尝试使用以下方法迭代列表:

for l1 in lst1:
   for i in l1:
       lst2.append(list(map(str.replace("(", ""), l1)))

I wanted the out result to be the same as original list of lists but without the parenthesis. 我希望out结果与原始列表列表相同但没有括号。 Also, I am looking for a method in editing lists of lists and not really a specific solution to this question. 此外,我正在寻找一种编辑列表列表的方法,而不是这个问题的具体解决方案。

Thank you, 谢谢,

Edit: 编辑:

Yes, you should use normal for-loops if you want to: 是的,如果你想:你应该使用普通的for循环:

  1. Preform multiple operations on each item contained in each sub-list. 对每个子列表中包含的每个项目执行多个操作。

  2. Keep both the main list as well as the sub-lists as the same objects. 将主列表和子列表保持为相同的对象。

Below is a simple demonstration of how to do this: 以下是如何执行此操作的简单演示:

main = [["(a)", "(b)", "(c)"], ["(d)", "(e)", "(f)", "(g)"]]

print id(main)
print id(main[0])
print id(main[1])
print

for sub in main:
    for index,item in enumerate(sub):

        ### Preform operations ###
        item = item.replace("(", "")
        item = item.replace(")", "")
        item *= 2

        sub[index] = item  # Reassign the item

print main
print
print id(main)
print id(main[0])
print id(main[1])

Output: 输出:

25321880
25321600
25276288

[['aa', 'bb', 'cc'], ['dd', 'ee', 'ff', 'gg']]

25321880
25321600
25276288

Use a nested list comprehension : 使用嵌套列表理解

>>> lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]
>>> id(lst1)
35863808
>>> lst1[:] = [[y.replace("(", "") for y in x] for x in lst1]
>>> lst1
[['a)', 'b)', 'c)'], ['d)', 'e)', 'f)', 'g)']]
>>> id(lst1)
35863808
>>>

The [:] will keep the list object the same. [:]将使列表对象保持不变。

I just did what you did, i used the fact that each element of a list can be assigned a new (or updated) value: 我只是做了你做的,我使用了这样一个事实,即列表的每个元素都可以分配一个新的(或更新的)值:

>>> lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]
>>> for x in range(len(lst1)):
        for y in range(len(lst1[x])):
            lst1[x][y] = lst1[x][y].replace("(", "")
>>> lst1
[['a)', 'b)', 'c)'], ['d)', 'e)', 'f)', 'g)']]

EDIT 编辑

This is how you do it with the "real problem" that you mentioned in the comment: 这就是你在评论中提到的“真正问题”的方法:

a = [[(12.22, 12.122, 0.000)], [(1232.11, 123.1231, 0.000)]]
some_num = 10
for x in range(len(a)):
    b = list(a[x][0])
    for y in range(len(b)):
        b[y] *= some_num
    a[x] = tuple(b)
print(a)

OUTPUT: OUTPUT:

[(122.2, 121.22, 0.0), (12321.099999999999, 1231.231, 0.0)]

^ All elements have been multiplied by a number and the original format is kept ^所有元素都乘以数字并保留原始格式

This is how it works: 这是它的工作原理:

So you have the initial list 'a' that has two sublists each with only ONE element (the tuple that contains the x,y,z coordinates). 所以你有一个初始列表'a',它有两个子列表,每个子列表只有一个元素(包含x,y,z坐标的元组)。 I go through list 'a' and make the tuples a list and set them equal to 'b' (so the fourth line has a value of [12.22, 12.122, 0.000] the first time around (and the next tuple (as a list) the next time around). 我浏览列表'a'并将元组设为列表并将它们设置为等于'b'(因此第四行的值第一次为[12.22,12.122,0.000](以及下一个元组(作为列表) )下一次)。

Then I go through each of the elements in 'b' (the tuple converted into a list) and multiply each element in that tuple by a number with the use of the increment operator (+=, -=, /=, *=). 然后我遍历'b'中的每个元素(元组转换为列表),并使用增量运算符将该元组中的每个元素乘以一个数字(+ =, - =,/ =,* =) 。 Once this loop is done, I set that same position in the master list 'a' equal to the tuple of the previously converted tuple. 完成此循环后,我将主列表中的相同位置'a'设置为等于先前转换的元组的元组。 < If this doesn't make sense, what I'm saying is that the initial tuples are converted into lists (then operated on), and then converter back to tuples (since you want it to end up with the same format as before). <如果这没有意义,我所说的是初始元组被转换为列表(然后进行操作),然后转换回元组(因为你希望它以与之前相同的格式结束) 。

Hope this helps! 希望这可以帮助!

>>> lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]
>>> [[j.strip('()') for j in i] for i in lst1]
[['a', 'b', 'c'], ['d', 'e', 'f', 'g']]
>>> [[j.lstrip('(') for j in i] for i in lst1]
[['a)', 'b)', 'c)'], ['d)', 'e)', 'f)', 'g)']]

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

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