[英]Iterating over lists of lists in Python
我有一份清單清單:
lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]
我想迭代每個元素並對它們執行一些字符串操作,例如:
replace("(", "")
我嘗試使用以下方法迭代列表:
for l1 in lst1:
for i in l1:
lst2.append(list(map(str.replace("(", ""), l1)))
我希望out結果與原始列表列表相同但沒有括號。 此外,我正在尋找一種編輯列表列表的方法,而不是這個問題的具體解決方案。
謝謝,
編輯:
是的,如果你想:你應該使用普通的for循環:
對每個子列表中包含的每個項目執行多個操作。
將主列表和子列表保持為相同的對象。
以下是如何執行此操作的簡單演示:
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])
輸出:
25321880
25321600
25276288
[['aa', 'bb', 'cc'], ['dd', 'ee', 'ff', 'gg']]
25321880
25321600
25276288
使用嵌套列表理解 :
>>> 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
>>>
[:]
將使列表對象保持不變。
我只是做了你做的,我使用了這樣一個事實,即列表的每個元素都可以分配一個新的(或更新的)值:
>>> 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)']]
編輯
這就是你在評論中提到的“真正問題”的方法:
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:
[(122.2, 121.22, 0.0), (12321.099999999999, 1231.231, 0.0)]
^所有元素都乘以數字並保留原始格式
這是它的工作原理:
所以你有一個初始列表'a',它有兩個子列表,每個子列表只有一個元素(包含x,y,z坐標的元組)。 我瀏覽列表'a'並將元組設為列表並將它們設置為等於'b'(因此第四行的值第一次為[12.22,12.122,0.000](以及下一個元組(作為列表) )下一次)。
然后我遍歷'b'中的每個元素(元組轉換為列表),並使用增量運算符將該元組中的每個元素乘以一個數字(+ =, - =,/ =,* =) 。 完成此循環后,我將主列表中的相同位置'a'設置為等於先前轉換的元組的元組。 <如果這沒有意義,我所說的是初始元組被轉換為列表(然后進行操作),然后轉換回元組(因為你希望它以與之前相同的格式結束) 。
希望這可以幫助!
>>> 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.