在for循环中修改嵌套列表项

时间:2020-04-18 10:03:54

标签: python list for-loop nested

我一直在尝试对嵌套列表执行几个简单的操作,但似乎找不到正确的方法。 这是列表的示例。

items_q = [['Place1','a=2','b=3','c=4','z=5','d=4'],
           ['Place2','a=2','b=3','c=4','z=5','f=4'],
           ['Place3','a=2','r=3','s=6'],
           ['Place2','a=2','r=3','s=4','z=5'],
           ['Place3','a=2','z=3','d=4']]

我需要提取两件事。一个是场所列表,另一个是从每个项目(字母)中剥离数量。我到目前为止:

places = []

for trx in items_q:
    places.append(trx[0])
    #print(trx[0])
    trx.pop(0)
    for i in trx:
        i = i[:-2]
        #print(i)

这“几乎”满足了我的所有需求。它创建一个位置列表,但不更改每个字母字符串的值(删除= x)。

输出应为:

items_q = [['a','b','c','z','d'],
           ['a','b','c','z','f'],
           ['a','r','s'],
           ['a','r','s','z'],
           ['a','z','d']]

places = ['Place1', 'Place2', 'Place3', 'Place2', 'Place3']

我意识到问题一定在于我们不能直接/就地修改列表。我需要创建一个新列表并附加值吗?我被困住了。

谢谢!

3 个答案:

答案 0 :(得分:2)

您需要遍历作为索引,而不使用值。

for trx in items_q:
    places.append(trx[0])
    trx.pop(0)
    for i in range(len(trx)): # i is now 0, 1, 2 … len(trx) - 1
        trx[i] = trx[i][:-2] # address the list using index

我建议将最后一行修改为trx[i] = trx[i].split("=")[0],这将说明项目名称具有多个字符(例如,'aa'不是'a'

答案 1 :(得分:1)

使用枚举功能可以更准确地处理每个索引:

全面:

places = []

for trx in items_q:
    places.append(trx[0])
    trx.remove(trx[0]) #Works similarly to Pop but doesn't return removed item in console

    for (index, value) in enumerate(trx):
        trx[i] = value[:-2]

print(items_q)
print(places)

这应该返回您想要的输出。

答案 2 :(得分:1)

您可以使用:

places = []
items = []

for p, *i in items_q:
    places.append(p)
    items.append([e[0] for e in i])

print(items)
print(places)

# [['a', 'b', 'c', 'z', 'd'], ['a', 'b', 'c', 'z', 'f'], ['a', 'r', 's'], ['a', 'r', 's', 'z'], ['a', 'z', 'd']]
# ['Place1', 'Place2', 'Place3', 'Place2', 'Place3']

如果要将项目保留在items_q变量中:

items_q = items