Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用元组索引列表?_Python_List_Indexing_Tuples - Fatal编程技术网

Python 如何使用元组索引列表?

Python 如何使用元组索引列表?,python,list,indexing,tuples,Python,List,Indexing,Tuples,我正在学习Python,遇到了以下示例: W = ((0,1,2),(3,4,5),(0,4,8),(2,4,6)) b = ['a','b','c','d','e','f','g','h','i'] for row in W: print b[row[0]], b[row[1]], b[row[2]] 其中打印: a、b、c d e f a e i c e g 我在想为什么 例如,我第一次通过扩展版本了解到: print b[(0,1,2)[0]], b[(0,1,2)[1]], b

我正在学习Python,遇到了以下示例:

W = ((0,1,2),(3,4,5),(0,4,8),(2,4,6))
b = ['a','b','c','d','e','f','g','h','i']
for row in W:
    print b[row[0]], b[row[1]], b[row[2]]
其中打印:

a、b、c

d e f

a e i

c e g

我在想为什么

例如,我第一次通过扩展版本了解到:

print b[(0,1,2)[0]], b[(0,1,2)[1]], b[(0,1,2)[2]]
但我不明白(0,1,2)是如何相互作用的。有人能解释一下吗?谢谢

(这是tic-tac-toe游戏的一些代码的缩写版本,它工作得很好,我只是不明白这部分)

在镜头中,
(0,1,2)
没有任何作用。它是一个元组,可以像列表一样索引,因此
b[(0,1,2)[0]
成为
b[0]
,因为
(0,1,2)[0]==0

在第一步中,Python执行
b[行[0]]
→ <代码>b[(0,1,2)[0]]→ <代码>b[0]→ <代码>'a'

顺便说一句,要一次从序列中获取多个项目,可以使用运算符:

from operator import itemgetter
for row in W:
    print itemgetter(*row)(b)

对元组进行索引只提取第n个元素,就像对数组进行索引一样。即扩展版本

print b[(0,1,2)[0]], b[(0,1,2)[1]], b[(0,1,2)[2]]
等于

print b[0], b[1], b[2]

也就是说,(0,1,2)元组(
(0,1,2)[0]
)的第0个元素是0。

它迭代一个元组元组,每个
都是一个三元素元组,打印时它通过索引访问
b
列表的三个元素,这就是
元组包含的内容

或许,一种稍微不那么杂乱的方法是:

for f, s, t in W:
    print b[f], b[s], b[t]

对于W中的行:

放入
行的第一个元组是
(0,1,2)

换句话说,
W[0]==(0,1,2)

因此,b='a'的第[0]个元素

b[0] == 'a'
等等

b[1] == 'b'
b[2] == 'c'

试着写下每个步骤中所有变量的值:你得到的结果是正确的

互动1:

  • 行为(0,1,2)
  • b[行[0]],b[行[1]],b[行[2]]是b[(0,1,2)[0],(0,1,2)[1],(0,1,2)[2]],==b[0],b[1],b[2]
互动2:

  • 行为(3,4,5)
  • b[行[0]],b[行[1]],b[行[2]]是b[3],b[4],b[5]

Python交互式shell将帮助您了解正在发生的事情:

In [78]: W = ((0,1,2),(3,4,5),(0,4,8),(2,4,6))

In [79]: b = ['a','b','c','d','e','f','g','h','i']

In [81]: row=W[0]       # The first time throught the for-loop, row equals W[0]

In [82]: row
Out[82]: (0, 1, 2)

In [83]: row[0]
Out[83]: 0

In [84]: b[row[0]]
Out[84]: 'a'

In [85]: b[row[1]]
Out[85]: 'b'

In [86]: b[row[2]]
Out[86]: 'c'

这令人困惑:“
行[0]==(0,1,2)
因此,
行[0]==0
”这很有帮助。我被卡在b[…]部分上,没有注意到(0,1,2)[0]部分本身就是一个操作——即索引元组。然后我试着在贝壳里用不同的变型做了那个部分,看到了返回的东西,然后我得到了它!谢谢。我是从另一篇文章中发现的,但我喜欢你的文章,因为你建议的方式更清晰一些。谢谢
In [78]: W = ((0,1,2),(3,4,5),(0,4,8),(2,4,6))

In [79]: b = ['a','b','c','d','e','f','g','h','i']

In [81]: row=W[0]       # The first time throught the for-loop, row equals W[0]

In [82]: row
Out[82]: (0, 1, 2)

In [83]: row[0]
Out[83]: 0

In [84]: b[row[0]]
Out[84]: 'a'

In [85]: b[row[1]]
Out[85]: 'b'

In [86]: b[row[2]]
Out[86]: 'c'