当前位置:首页 » 编程语言 » python多维列表

python多维列表

发布时间: 2022-04-26 10:50:07

A. 想问下python中 多维列表和一维列表之间怎么判断呢

如果是每个都要检查并返回可以参考下面这个结构

B. python大神你好,请问二维列表参照一维列表排序的问题。

list1.sort(key=lambda x: list2.index(x[1]))

C. python 在二维列表中查找出包含指定值的子列表

如果 list 存储了若干复杂结构的值,比如这样的一个列表:
temp = [('a', 1, 1.5),
('b', 2, 5.1),
('c', 9, 4.3)]

你想找到其中是 ('b', XX, XX) 这样的元素,其中 XX 可以为任意值。这种情况无法通过 index 函数来获得,我们可以利用 sort 的 key 参数来实现。
list.sort(或者 sorted 函数)有一个 key 参数,你可以提供一个函数来作为排序的依据。此时我们可以传入以下值:
temp.sort(key = lambda x:x[0]!='b')

随后我们会发现,所有形如 ('b', XX, XX) 的元素全部浮动到了列表的头部,此时我们访问 temp[0] 就可以获得想要查找的值了。
我们也可以写一个简单的函数:
findindex = lambda self,i,value:sorted(self,key=lambda x:x[i]!=value)[0]

那我们只需要这样调用:
>>> findindex(temp,0,'b')

就会返回它找到的第一个值:
>>> ('b',2)

D. python 使用嵌套的for循环创建二维列表

因为你一开始的arr只是一个一维列表[],所以第一个循环其实是为第二个循环准备需要用到的空列表,你要是append(x)的话相当于arr在第一层第一个循环后变成[0],然后在第二层的循环里arr[x]=arr[0]=0就是一个数,没办法append

E. python如何将多维字典每个键的值转换成多维列表

定义一个递归函数就行了,下面是一个例子:

def get(d):

l=[]

for k,v in d.items():

if isinstance(v,dict):

l.append(get(v))

else:

l.append(v)

return l

d={"1":"2","a":{"b":{"c":"1"}},"b":"c"}

l=get(d)

print(l)

这是运行截图:

F. python生成器是怎么使用的

生成器(generator)概念
生成器不会把结果保存在一个系列中,而是保存生成器的状态,在每次进行迭代时返回一个值,直到遇到StopIteration异常结束。
生成器语法
生成器表达式: 通列表解析语法,只不过把列表解析的[]换成()
生成器表达式能做的事情列表解析基本都能处理,只不过在需要处理的序列比较大时,列表解析比较费内存。

Python

1
2
3
4
5
6
7
8
9
10
11

>>> gen = (x**2 for x in range(5))
>>> gen
<generator object <genexpr> at 0x0000000002FB7B40>
>>> for g in gen:
... print(g, end='-')
...
0-1-4-9-16-
>>> for x in [0,1,2,3,4,5]:
... print(x, end='-')
...
0-1-2-3-4-5-

生成器函数: 在函数中如果出现了yield关键字,那么该函数就不再是普通函数,而是生成器函数。
但是生成器函数可以生产一个无线的序列,这样列表根本没有办法进行处理。
yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,Python 解释器会将其视为一个 generator。
下面为一个可以无穷生产奇数的生成器函数。

Python

1
2
3
4
5
6
7
8
9
10
11

def odd():
n=1
while True:
yield n
n+=2
odd_num = odd()
count = 0
for o in odd_num:
if count >=5: break
print(o)
count +=1

当然通过手动编写迭代器可以实现类似的效果,只不过生成器更加直观易懂

Python

1
2
3
4
5
6
7
8
9
10
11

class Iter:
def __init__(self):
self.start=-1
def __iter__(self):
return self
def __next__(self):
self.start +=2
return self.start
I = Iter()
for count in range(5):
print(next(I))

题外话: 生成器是包含有__iter()和next__()方法的,所以可以直接使用for来迭代,而没有包含StopIteration的自编Iter来只能通过手动循环来迭代。

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

>>> from collections import Iterable
>>> from collections import Iterator
>>> isinstance(odd_num, Iterable)
True
>>> isinstance(odd_num, Iterator)
True
>>> iter(odd_num) is odd_num
True
>>> help(odd_num)
Help on generator object:

odd = class generator(object)
| Methods defined here:
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
......

看到上面的结果,现在你可以很有信心的按照Iterator的方式进行循环了吧!
在 for 循环执行时,每次循环都会执行 fab 函数内部的代码,执行到 yield b 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield。看起来就好像一个函数在正常执行的过程中被 yield 中断了数次,每次中断都会通过 yield 返回当前的迭代值。

yield 与 return
在一个生成器中,如果没有return,则默认执行到函数完毕时返回StopIteration;

Python

1
2
3
4
5
6
7
8
9
10
11

>>> def g1():
... yield 1
...
>>> g=g1()
>>> next(g) #第一次调用next(g)时,会在执行完yield语句后挂起,所以此时程序并没有执行结束。
1
>>> next(g) #程序试图从yield语句的下一条语句开始执行,发现已经到了结尾,所以抛出StopIteration异常。
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
StopIteration
>>>

如果遇到return,如果在执行过程中 return,则直接抛出 StopIteration 终止迭代。

Python

1
2
3
4
5
6
7
8
9
10
11
12

>>> def g2():
... yield 'a'
... return
... yield 'b'
...
>>> g=g2()
>>> next(g) #程序停留在执行完yield 'a'语句后的位置。
'a'
>>> next(g) #程序发现下一条语句是return,所以抛出StopIteration异常,这样yield 'b'语句永远也不会执行。
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
StopIteration

如果在return后返回一个值,那么这个值为StopIteration异常的说明,不是程序的返回值。
生成器没有办法使用return来返回值。

Python

1
2
3
4
5
6
7
8
9
10
11

>>> def g3():
... yield 'hello'
... return 'world'
...
>>> g=g3()
>>> next(g)
'hello'
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
StopIteration: world

生成器支持的方法

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

>>> help(odd_num)
Help on generator object:

odd = class generator(object)
| Methods defined here:
......
| close(...)
| close() -> raise GeneratorExit inside generator.
|
| send(...)
| send(arg) -> send 'arg' into generator,
| return next yielded value or raise StopIteration.
|
| throw(...)
| throw(typ[,val[,tb]]) -> raise exception in generator,
| return next yielded value or raise StopIteration.
......

close()
手动关闭生成器函数,后面的调用会直接返回StopIteration异常。

Python

1
2
3
4
5
6
7
8
9
10
11
12
13

>>> def g4():
... yield 1
... yield 2
... yield 3
...
>>> g=g4()
>>> next(g)
1
>>> g.close()
>>> next(g) #关闭后,yield 2和yield 3语句将不再起作用
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
StopIteration

send()
生成器函数最大的特点是可以接受外部传入的一个变量,并根据变量内容计算结果后返回。
这是生成器函数最难理解的地方,也是最重要的地方,实现后面我会讲到的协程就全靠它了。

Python

1
2
3
4
5
6
7
8
9
10
11
12
13

def gen():
value=0
while True:
receive=yield value
if receive=='e':
break
value = 'got: %s' % receive

g=gen()
print(g.send(None))
print(g.send('aaa'))
print(g.send(3))
print(g.send('e'))

执行流程:
通过g.send(None)或者next(g)可以启动生成器函数,并执行到第一个yield语句结束的位置。此时,执行完了yield语句,但是没有给receive赋值。yield value会输出初始值0注意:在启动生成器函数时只能send(None),如果试图输入其它的值都会得到错误提示信息。
通过g.send(‘aaa’),会传入aaa,并赋值给receive,然后计算出value的值,并回到while头部,执行yield value语句有停止。此时yield value会输出”got: aaa”,然后挂起。
通过g.send(3),会重复第2步,最后输出结果为”got: 3″
当我们g.send(‘e’)时,程序会执行break然后推出循环,最后整个函数执行完毕,所以会得到StopIteration异常。
最后的执行结果如下:

Python

1
2
3
4
5
6
7

0
got: aaa
got: 3
Traceback (most recent call last):
File "h.py", line 14, in <mole>
print(g.send('e'))
StopIteration

throw()
用来向生成器函数送入一个异常,可以结束系统定义的异常,或者自定义的异常。
throw()后直接跑出异常并结束程序,或者消耗掉一个yield,或者在没有下一个yield的时候直接进行到程序的结尾。

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

def gen():
while True:
try:
yield 'normal value'
yield 'normal value 2'
print('here')
except ValueError:
print('we got ValueError here')
except TypeError:
break

g=gen()
print(next(g))
print(g.throw(ValueError))
print(next(g))
print(g.throw(TypeError))

输出结果为:

Python

1
2
3
4
5
6
7
8

normal value
we got ValueError here
normal value
normal value 2
Traceback (most recent call last):
File "h.py", line 15, in <mole>
print(g.throw(TypeError))
StopIteration

解释:
print(next(g)):会输出normal value,并停留在yield ‘normal value 2’之前。
由于执行了g.throw(ValueError),所以会跳过所有后续的try语句,也就是说yield ‘normal value 2’不会被执行,然后进入到except语句,打印出we got ValueError here。然后再次进入到while语句部分,消耗一个yield,所以会输出normal value。
print(next(g)),会执行yield ‘normal value 2’语句,并停留在执行完该语句后的位置。
g.throw(TypeError):会跳出try语句,从而print(‘here’)不会被执行,然后执行break语句,跳出while循环,然后到达程序结尾,所以跑出StopIteration异常。
下面给出一个综合例子,用来把一个多维列表展开,或者说扁平化多维列表)

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

def flatten(nested):

try:
#如果是字符串,那么手动抛出TypeError。
if isinstance(nested, str):
raise TypeError
for sublist in nested:
#yield flatten(sublist)
for element in flatten(sublist):
#yield element
print('got:', element)
except TypeError:
#print('here')
yield nested

L=['aaadf',[1,2,3],2,4,[5,[6,[8,[9]],'ddf'],7]]
for num in flatten(L):
print(num)

如果理解起来有点困难,那么把print语句的注释打开在进行查看就比较明了了。

总结
按照鸭子模型理论,生成器就是一种迭代器,可以使用for进行迭代。
第一次执行next(generator)时,会执行完yield语句后程序进行挂起,所有的参数和状态会进行保存。再一次执行next(generator)时,会从挂起的状态开始往后执行。在遇到程序的结尾或者遇到StopIteration时,循环结束。
可以通过generator.send(arg)来传入参数,这是协程模型。
可以通过generator.throw(exception)来传入一个异常。throw语句会消耗掉一个yield。可以通过generator.close()来手动关闭生成器。
next()等价于send(None)

G. python中二维列表取值

为了便于你理解,我写了这样的代码,主要工作是使用循环条件遍历二维列表,然后取出我们想要的内容,比如你说的b。以下是代码,你参考下:

至少python3.6环境

#以下代码至少运行于python3.6
#定义函数
defgetArrayList(alist):
istr=input('请输入要在二维列表中查找的内容:')
foriinrange(len(alist)):#遍历alist,返回alist对象的项目数
forjinrange(len(alist[i])):#遍历alist[i],返回alist[i]对象的项目数
ifalist[i][j]==str(istr):#判断是否找到数据
#找到的话输出
print('在二维列表'f"{alist}"'中找到alist'f"{[i,j]}:",alist[i][j])
returnTrue
print('没找到相关数据!')
returnFalse

#定义程序主入口
if__name__=='__main__':
arraylist=[['a','b','c'],['d','e'],['f']]#初始化二维列表
getArrayList(arraylist)#调用函数

python3环境

#以下代码运行于python3
#定义函数
defgetArrayList(alist):
istr=input('请输入要在二维列表中查找的内容:')
foriinrange(len(alist)):#遍历alist,返回alist对象的项目数
forjinrange(len(alist[i])):#遍历alist[i],返回alist[i]对象的项目数
ifalist[i][j]==str(istr):#判断是否找到数据
#找到的话输出
print('在二维列表{}'.format(alist)+'中找到alist({},{})'.format(i,j)+':',alist[i][j])
returnTrue
print('没找到相关数据!')
returnFalse

#定义程序主入口
if__name__=='__main__':
arraylist=[['a','b','c'],['d','e'],['f']]#初始化二维列表
getArrayList(arraylist)#调用函数

或,我们还可以这样

python3环境

#以下代码运行于python3
#定义函数
defgetArrayList(alist):
print(alist)#打印二维列表方便对比
i,j=0,1#初始化i,j
result=alist[i][j]#用二维索引的方式找出b
returnresult

#定义程序主入口
if__name__=='__main__':
arraylist=[['a','b','c'],['d','e'],['f']]#初始化二维列表
print('取出:',getArrayList(arraylist))#调用函数

使用切片是最方便的,其实还可以类似这样:

result=alist[0:1][0:1] #取出子矩阵

注:你所提的这个问题,用到了数学,所以对数学了解的话,写出来的代码更简洁。我给你写的代码你还可以更完善。

纯手工,如果对你有帮助望采纳!

H. python基础题(选择排序、二维列表)如何做,急求


from random import sample
data=sample(range(1,101),30)
arr=[data[x:x+6] for x in range(0,len(data),6)]
print('转变为5*6的二维列表',arr,' ')
print('该二维列表每行最大值:',list(map(max,arr)),' ')
print('该二维列表每行最小值:',list(map(min,arr)),' ')
print('该二维列表每行平均值:',list(map(lambda x:sum(x)/len(x),arr)),' ')
print('大于平均值个数:',list(map(lambda x:len([y for y in x if y>sum(x)/len(x)]),arr)),' ')
print('小于平均值个数:',list(map(lambda x:len([y for y in x if y<sum(x)/len(x)]),arr)))

I. 如何在python中创建二维列表

Python中创建二维列表/数组,即创建一个list,并且这个list的元素还是list。可以用列表解析的方法实现。

创建例子如下:

2d_list=[[0forcolinrange(cols)]forrowinrange(rows)]

其中cols, rows变量替换为你需要的数值即可,例如:

2d_list=[[0forcolinrange(9)]forrowinrange(9)]
#9*9的二维列表
热点内容
网吧u盘拒绝访问 发布:2025-05-16 14:13:50 浏览:259
无线网检查网络配置是怎么回事 发布:2025-05-16 14:04:03 浏览:220
网络爬虫python代码 发布:2025-05-16 14:03:26 浏览:516
汽车小组件怎么弄到安卓桌面 发布:2025-05-16 13:51:12 浏览:220
linuxg编译器下载 发布:2025-05-16 13:50:58 浏览:776
centosc编译器 发布:2025-05-16 13:50:17 浏览:948
安卓手机如何变换桌面 发布:2025-05-16 13:39:33 浏览:515
sql存储过程命令 发布:2025-05-16 13:17:54 浏览:146
用纸做解压小玩具西瓜 发布:2025-05-16 13:04:09 浏览:936
局域网xp无法访问win7 发布:2025-05-16 13:03:58 浏览:943