python元组操作实例解析

WBOY
Release: 2016-06-06 11:32:58
Original
1541 people have browsed it

本文实例讲述了python元组操作方法,分享给大家供大家参考。具体分析如下:

一般来说,python的函数用法挺灵活的,和c、php的用法不太一样,和js倒是挺像的。

在照着操作时,可以发现一个很神奇的现象:

>>> t = (1, 3, 'b')
>>> q = t + ((3, 'abc'))
>>> q
(1, 3, 'b', 3, 'abc')

Copy after login

这里我预料的应该是(1, 3, 'b', (3, 'abc')),但是结果却是(1, 3, 'b', 3, 'abc'),刚开始我猜测python是把所有的元素都提取出来重新按原顺序组合。然后我又试了一下:

>>> q = t + ((3, 'abc'), '3')
>>> q
(1, 3, 'b', (3, 'abc'), '3')
Copy after login

看来猜测错了,那为什么q = t + ((3, 'abc'))就把元组拆分了呢,我又试了一下:

>>> q = t + ((3, 'abc', ('a')))
>>> q
(1, 3, 'b', 3, 'abc', 'a')
Copy after login

python又把元素里的元组里的('a')去掉了(),为了验证我的想法,我进一步测试:

>>> q = t + ((3, 'abc', ('a', 'ab')))
>>> q
(1, 3, 'b', 3, 'abc', ('a', 'ab'))
Copy after login

看来结果已经很明了了,在对元组进行+操作时,python会自动对被加的元组进行解析,在保持原元组结构的前提下,把它解析成最简单的元组进行相加,即把只有单一元素的多重元组去括号。
那么,如果我不想让python在+操作时把()去掉呢,那么这样操作就行了:

>>> q = t + ((3, 'abc'),)
>>> q
(1, 3, 'b', (3, 'abc'))
Copy after login

希望本文所述对大家Python程序设计的学习有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!