小编Cod*_*nja的帖子

如何根据python中的不同条件动态创建列表?

文本文件:

Animals
  Tiger
  Lion
    Cat
      Mice
Birds
  Parrot
  Peacock
    Hen
      chicken
Reptiles
Mammals
Run Code Online (Sandbox Code Playgroud)

我想根据缩进动态分离单词并将其存储在不同的列表中

预期输出:

a=['Animals','Birds','Reptiles','Mammals']
b=['Tiger','Lion','Parrot','Peacock']
c=['Cat','Hen']
d=['Mice','Chicken']
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

a=[]
b=[]
c=[]
d=[]
for i in text:
  indent = len(i)-len(i.lstrip())
  if indent == 0:
    a.append(i)
  if indent == 2:
    b.append(i)
  if indent == 4:
    c.append(i)
  if indent == 6:
    d.append(i)        
Run Code Online (Sandbox Code Playgroud)

它提供了预期的输出,但我希望它采用动态方法。

python dictionary list indentation python-3.x

2
推荐指数
1
解决办法
103
查看次数

标签 统计

dictionary ×1

indentation ×1

list ×1

python ×1

python-3.x ×1