迭代Python列表是否可能包括其他列表?

2024-05-14 21:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个接受两个参数的函数。我想迭代一系列成对的参数,对每一对参数进行调用:

arglist = [(arg1, 'Ni!'), (arg2, 'Peng!'), (arg3, 'Neee-Wom!')]
for arg in arglist:
    func(arg[0], arg[1])

# The pairs don't have to be tuples, just showing that way for convenience

这里是一个转折点——我希望每对中有一个参数有时是一个列表,在这种情况下,整个迭代将遍历列表中的每个项目,调用其上的函数及其伙伴。因此:

newwords = ['Ekke', 'ekke', 'Ptang', 'Zoo', 'Boing']
arglist = [(arg1, 'Ni!'), (arg2, 'Peng!'), (arg3, 'Neee-Wom!'), (arg4, newwords)]
for arg in arglist:
    func(arg[0], arg[1])

应等同于此:

arglist = [(arg1, 'Ni!'), (arg2, 'Peng!'), (arg3, 'Neee-Wom!'), (arg4, 'Ekke'), 
           (arg4, 'Ekke'), (arg4, 'Ptang'), (arg4, 'Zoo'), (arg4, 'Boing')]
for arg in arglist:
    func(arg[0], arg[1])

有没有一种很好的Python式的方法


Tags: infor参数argarg3funcarg1arg2
3条回答

试试这个:

for arg, value in arglist:
    if isinstance(value, list):
        for v in value:
            func(arg, v)
    else:
        func(arg, value)

取决于该列表成对出现的频率

如果频繁-尝试-除非

def try_except_method():
    for arg, item in args_list:
        try:
            for i in item:  # assuming item is following sequence protocol.
                do_something(arg, i)
        except TypeError:  # asking for forgiveness.
            do_something(arg, item)

在每次迭代中,这将比测试条件运行得更快

如果不是,则使用“isinstance”检查条件,就像其他答案一样

def is_instance_method():
    for arg, item in args_list:
        if isinstance(item, list):
            for i in item:
                do_something(arg, i)
        else:
            do_something(arg, item)

如果您计划使用除列表和str以外的更多类型,则可获得额外奖励- 选择“单发”

@singledispatch  # all types other than registers goes here.
def func(a, b):
    do_something(a, b)


@func.register(list)  # only list type goes here.
def func_list(a, b):
    for i in b:
        do_something(a, i)


def single_dispatched():
    for arg, item in args_list:
        func(arg, item)

每个方法所用时间的结果与示例一起。 试着用不同的数据处理它们,这里是full code

0.0021587999999999052
0.0009472000000001479
0.0024591000000000474

isinstance()是一个可以帮助你做到这一点的人

您可以做的是,使用isinstance()检查它是否是一个列表。和你可能的功能

for arg in arglist:
  # if the item is a list go through each item and pass it with the arg[0]
  if isinstance(arg[1], type([])): 
      # passing arg[0] and item from array item of arg[0]
      for item in arg[1]: func(arg[0], item) 
  else: func(arg[0], arg[1])

希望对你有帮助。如需更多澄清,请随时提问:)在此之前,祝您学习愉快

相关问题 更多 >

    热门问题