【问题标题】:Looping through list and nested lists in python在python中循环遍历列表和嵌套列表
【发布时间】:2023-03-25 05:55:01
【问题描述】:

我正在尝试为 Python 中的字符串列表添加前缀。字符串列表可能包含多层嵌套列表。

有没有办法在保持结构的同时遍历这个列表(及其嵌套列表)?

嵌套的 for 循环很快变得不可读,而且似乎不是正确的方法..

list = ['a', 'b', ['C', 'C'], 'd', ['E', ['Ee', 'Ee']]]

for i in list:
        if isinstance(i, list):
                for a in i:
                        a = prefix + a
                        #add more layers of for loops
        else:
                i = prefix + i

期望的结果:

prefix = "#"
newlist = ['#a', '#b', ['#C', '#C'], '#d', ['#E', ['#Ee', '#Ee']]]

提前致谢!

【问题讨论】:

标签: python loops nested-loops


【解决方案1】:

你可以写一个简单的递归函数

def apply_prefix(l, prefix):
    # Base Case
    if isinstance(l, str):
        return prefix + l
    # Recursive Case
    else:
        return [apply_prefix(i, prefix) for i in l]


l = ['a', 'b', ['C', 'C'], 'd', ['E', ['Ee', 'Ee',]]]

print(apply_prefix(l, "#"))
# ['#a', '#b', ['#C', '#C'], '#d', ['#E', ['#Ee', '#Ee']]]

【讨论】:

    【解决方案2】:

    这将使用递归:

    a = ['a', 'b', ['C', 'C'], 'd', ['E', ['Ee', 'Ee',]]]
    
    
    def insert_symbol(structure, symbol='#'):
        if isinstance(structure, list):
            return [insert_symbol(sub_structure) for sub_structure in structure]
        else:
            return symbol + structure
    
    print(insert_symbol(a))
    
    >>> ['#a', '#b', ['#C', '#C'], '#d', ['#E', ['#Ee', '#Ee']]]
    

    【讨论】:

      【解决方案3】:

      你可以使用这样的递归代码!,试试看,如果你有问题可以问我

      def add_prefix(input_list):
          changed_list = []
          for elem in input_list:
              if isinstance(elem, list):
                  elem = add_prefix(elem)
                  changed_list.append(elem)
              else:
                  elem = "#" + elem
                  changed_list.append(elem)
          return changed_list
      

      【讨论】:

        【解决方案4】:

        也许您可以使用函数递归地执行此操作。

        list_example = ['a', 'b', ['C', 'C'], 'd', ['E', ['Ee', 'Ee']]]
        
        def add_prefix(p_list, prefix):
            for idx in range(len(p_list)):
                if isinstance(p_list[idx], list):
                    p_list[idx] = add_prefix(p_list[idx], prefix)
                else:
                    p_list[idx] = prefix + p_list[idx]
            return p_list
        
        add_prefix(list_example, '#')
        

        编辑:我现在看到有人发布了几乎相同的内容。

        顺便说一句。命名列表列表被认为是不好的做法,因为它也是 python 中的类型名。可能会导致不良行为

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-04-26
          • 1970-01-01
          • 2018-10-26
          • 2019-04-15
          • 1970-01-01
          • 1970-01-01
          • 2012-11-11
          相关资源
          最近更新 更多