如何在列表中附加子列表?

时间:2018-09-13 09:30:31

标签: python list

我要做的就是创建1个包含所有这些值的列表,而不包含子列表。

example = ['a', ['c', 1, 3], ['f', 7, [4, '4']], [{'lalala': 111}]]
newArray = []

def func(array):
    for i in array:
        for z in i:
            newArray.append(z)

print(func(example))

这里的结果将是:['a','c',1,3,'f',7,[4,'4'],{'lalala':111}]。 当我添加3rd时,它会说“ int”对象不可迭代。我是否需要以某种方式检查项目是int还是string,然后跳过它们?还是我错过了什么?

P.S。我相信这是通过递归函数完成的,但是我对它们一无所知:(

5 个答案:

答案 0 :(得分:2)

这是递归函数使列表变平的一个示例:

def flatten(l):
    if type(l) is list:
        if not l:
            return []
        if len(l) == 1 :
            return flatten(l[0])
        else:
            return flatten(l[0]) + flatten(l[1:])
    else:
        return [l]

结果为['a','c',1,3,'f',7,4,'4',{'lalala':111}]

答案 1 :(得分:1)

使用递归函数。享受吧!

代码:

#!/bin/bash
urlPattern='/demo/([^\s]+)/'
if grep -qP "$urlPattern" <<< "/demo/akash/"; then
  echo "match"
else
  echo "not match"
fi

输出:

a <- c("C","A","A","B","A","C","C")
b <- c(1,1,2,1,2,1,2)
df <-data.frame(a,b)

library(dplyr)

df %>%
  group_by(a,b) %>%    # for each combination of a and b
  mutate(c = n()) %>%  # count times they appear
  ungroup()

# # A tibble: 7 x 3
#   a         b     c
#   <fct> <dbl> <int>
# 1 C         1     2
# 2 A         1     1
# 3 A         2     2
# 4 B         1     1
# 5 A         2     2
# 6 C         1     2
# 7 C         2     1

如果您不希望字典保留为字典,而只希望值。您可以使用它。但是,如果您想保留密钥,则只需使用:

example = ['a', ['c', 1, 3], ['f', 7, [4, '4']], [{'lalala': 111}]]
newArray = [] 

def super_extend(v):
        if type(v) is list:
            [super_extend(x) for x in v if x is not None]
        if type(v) is dict:
            {k:super_extend(v) for k,v in v.items() if v is not None}
        if type(v) is str or isinstance(v, int) or isinstance(v, float) :
            newArray.append(v)

super_extend(example)
print(newArray)

那么输出将是:

['a', 'c', 1, 3, 'f', 7, 4, '4', 111]
[Finished in 0.078s]

答案 2 :(得分:1)

使用递归生成器函数:

-1

答案 3 :(得分:0)

列表方法

list对象提供了两种不同的方法来将新项目添加到给定的list

  1. list.append(x):将项目添加到列表的末尾。等效于a [len(a):] = [x]。

  2. list.extend(iterable):通过附加可迭代项中的所有项来扩展列表。等效于a [len(a):] =可迭代。

示例

old_list = ['a', ['c', 1, 3], ['f', 7, [4, '4']], [{'lalala': 111}]]
new_list = []

for element in old_list:
    new_list.extend(element)

print(new_list)

结果

['a', 'c', 1, 3, 'f', 7, [4, '4'], {'lalala': 111}]

答案 4 :(得分:0)

也许您正在寻找这样的东西:

example = ['a', ['c', 1, 3], ['f', 7, [4, '4']], [{'lalala': 111}]]

def func(array):
    newArray = []
    for i in array:
        if((type(i)==int) or (type(i)==str)):
            newArray.append(i)
        elif(type(i)==dict ):
            keys = i.keys()
            values = i.values()
            newArray.append(keys[0])
            newArray.append(values[0])
        else:
            for z in i:            
                newArray.append(z)
    return newArray

print(func(example))
print(func(func(example)))
print(func(func(func(example))))

结果:

['a', 'c', 1, 3, 'f', 7, [4, '4'], {'lalala': 111}]
['a', 'c', 1, 3, 'f', 7, 4, '4', 'lalala', 111]
['a', 'c', 1, 3, 'f', 7, 4, '4', 'lalala', 111]