定义及基本操作

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

# 类Card,具有'rank', 'suit'两个属性

Card = collections.namedtuple('Card', ['rank', 'suit'])
#也可以用Card = collections.namedtuple('Card', "rank suit")


aaanz = Card('514', 'gagaga')
anz = Card('114', ['biu','da'])

print(Card._fields)
print(aaanz.suit)
print(anz.suit)
print(anz[0])

# ('rank', 'suit')
# gagaga
# ['biu', 'da']
# 114

嵌套

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


Card = collections.namedtuple('Card', ['rank', 'suit'])

anz = Card('114', ['biu','da'])

Tao=collections.namedtuple('Tao', "yi er")

test=('aa',anz)
make=Tao._make(test)
print(make)

#Tao(yi='aa', er=Card(rank='114', suit=['biu', 'da']))

打印输出

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


Card = collections.namedtuple('Card', ['rank', 'suit'])
#也可以用Card = collections.namedtuple('Card', "rank suit")

anz = Card('114', ['biu','da'])

Tao=collections.namedtuple('Tao', "yi er")

test=('aa',anz)
make=Tao._make(test)
#print(make)

for key, value in make._asdict().items():
print(key + ':', value)
# yi: aa
# er: Card(rank='114', suit=['biu', 'da'])