pythonlist嵌套
⑴ list可以嵌套吗 python
可以
>>> a=[]
>>> a.append(a)
>>> a
[[...]]
⑵ python 嵌套list读取
b1=[[2]*3]*2
b2=[[2,2,2],[2,2,2]]
这个两个定义的变量其实时不一样的
b2一个list,包含两个list元素
b1是1个list元素的两个浅拷贝,可以理解成两个指向[2]*3的指针。
出现这种问题,实际上理解的误区,[2]*3
=
[2,2,2]
就想当然的把[[2]*3]*2=
[2,2,2]*2
=
[[2,2,2]
[2,2,2]]
其实[[]]是一个list的浅拷贝(或者理解成指向list指针)
更详细的可以看下python的文档,里面有说明。
⑶ Python怎么拉平嵌套列表
Python如何拉平(flatten)嵌套列表(nested
list)
有时候会用到嵌套的列表(list),比如
[1,
2,
[3,
4,
[5,
6]],
["abc",
"def"]]
如果将嵌套的列表拉平(flatten)呢?变成:
[1,
2,
3,
4,
5,
6,
"abc",
"def"]
方法有很多,目前了解到的各方面都比较好,也很pythonic的方法是:
def
flatten(l):
for
el
in
l:
if
hasattr(el,
"__iter__")
and
not
isinstance(el,
basestring):
for
sub
in
flatten(el):
yield
sub
else:
yield
el
l
=
[1,
2,
[3,
4,
[5,
6]],
["abc",
"def"]]
l2
=
[x
for
x
in
flatten(l)]
print
l2
#[1,
2,
3,
4,
5,
6,
"abc",
"def"]
⑷ python 嵌套list
defiseven(l):
foriinl:
ifi%2:
returnFalse
returnTrue
defonly_evens(ll):
r=[]
foriinll:
ifiseven(i):
r.append(i)
returnr
printonly_evens([[1,2,4],[4,0,6],[22,4,3],[2]])
Python 2.7 执行结果
[[4, 0, 6], [2]]
其中 iseven 函数判断 list 是不是都是偶数
⑸ Python中嵌套list使用append的问题
你这样写代码会把脑袋绕晕
请举一个有点实际意义的例子(用有意义的变量名)
⑹ 关于Python列表嵌套问题
这个叫元组的拆包或解包。
list1迭代返回的是元组,那么for循环内就是
m,n = ('c',1)
m,n = ('Python',2)
...
⑺ python列表的嵌套该怎么理解
不对…
这里
[row[i] for row in matrix] for i in range(4)
是一个整体,不然row[i] for row in matrix里的i是哪来的…
这个List Comprehension相当于一个嵌套循环,外层循环变量是i,内层循环变量是row。
把列表的外层循环改为普通for循环的话,等价于:
temp_list = []
for i in range(4):
temp_list.append([row[i] for row in matrix])
把列表的两层循环都改为普通for循环写法,大致相当于:
temp_list = []
for i in range(4):
temp_list.append([])
for row in matrix:
temp_list[-1].append(row[i])
⑻ python 将两个list合并成为一个嵌套的list
除了直接相加(生成新的list),还有两种方法(修改其中一个list):
用list的extend方法,L1.extend(L2),该方法将参数L2的全部元素添加到L1的尾部,例如:
1
2
3
4
5
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>> L1.extend(L2)
>>> L1
[1, 2, 3, 4, 5, 20, 30, 40]
用切片(slice)操作,L1[len(L1):len(L1)] = L2和上面的方法等价,例如:
1
2
3
4
5
6
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>> L1[len(L1):len(L1)] = L2
>>>
>>> L1
[1, 2, 3, 4, 5, 20, 30, 40]
但切片方法用起来更灵活,可以插入到头部,或其他任意部位,例如:
加到开头:
1
2
3
4
5
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>> L1[0:0] = L2
>>> L1
[20, 30, 40, 1, 2, 3, 4, 5]
加到中间:
1
2
3
4
5
6
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>>
>>> L1[1:1] = L2
>>> L1
[1, 20, 30, 40, 2, 3, 4, 5]
参考
1.《python libarary referece》5.6.4. Mutable Sequence Types:
(oschina文档镜像地址)http://tool.oschina.net/uploads/apidocs/python2.7.3/library/stdtypes.html#mutable-sequence-types
⑼ 请教python列表嵌套问题
可以这样写:
l=[{'name':'张三','性别':'男','年龄':12,'成绩':60},{'name':'张三','性别':'女','年龄':12,'成绩':80},{'name':'李四','性别':'男','年龄':13,'成绩':75},{'name':'王五','性别':'男','年龄':12,'成绩':20}]
l=list(filter(lambda d:d['name']=='张三',l))
print(l)
这是运行截图:
⑽ 如何使用Python3实现嵌套List中的元素两两相乘
一、
AList=[[5,8],[3,6],[4,5],[3,8],[6,2]]
foriinrange(len(AList)):
AList.append(AList[0][0]*AList[0][1])
temp=AList.pop(0)
print("AList="+str(AList))
二、
AList=[[5,8],[3,6],[4,5],[3,8],[6,2]]
foriinAList:
AList_Fist.append(i[0])
print("AList_Fist="+str(AList_Fist))