1. 两个元素互换位置
a
=
[
1
,
2
]
print
(
a
)
a
[
0
]
,
a
[
1
]
=
a
[
1
]
,
a
[
0
]
print
(
a
)
列表是可变对象,变动里面的元素本身的id不会发生变化,以下代码说明了问题。
oneSimpleList
=
[
1
,
2
]
a
=
oneSimpleList
print
(
id
(
a
)
,
id
(
oneSimpleList
)
)
print
(
a
,
oneSimpleList
)
a
[
0
]
,
a
[
1
]
=
a
[
1
]
,
a
[
0
]
print
(
a
,
oneSimpleList
)
print
(
id
(
a
)
,
id
(
oneSimpleList
)
)
2. 四个元素互换位置
a
=
[
1
,
2
,
3
,
4
]
print
(
a
)
a
[
0
]
,
a
[
1
]
,
a
[
2
]
,
a
[
3
]
=
a
[
2
]
,
a
[
3
]
,
a
[
0
]
,
a
[
1
]
print
(
a
)