Python代码库之Tuple如何append添加元素问题

作者:知识大胖 时间:2021-10-02 07:13:34 

Python 代码库之Tuple如何append元素

tuple不像array给我们提供了append函数,我们可以通过下面的方式添加

t=[1,3,4,5]                                                            
k=()
for item in t:
   k=k+(item,)

Python tuple与list、append与extend

tuple 里边的 list 可修改:

>> t = (1, 2, [3, 4])
>>t[2].append(5)
>> t 
(1, 2, [3, 4, 5])

tuple的切片还是tuple,list的切片还是list(这可能是一句废话)

>>>type(t[0:2])
<class 'tuple'>
>>>type(l[0:3])
<class 'list'>

1. tuple可读不可写

tuple的元素不可作左值,list反之

>>>t = (1, 2, 3)
>>>t[:]
(1, 2, 3)

>>>t[0] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>>l = [1, 2, 3]
>>>l[:]
[1, 2, 3]
>
>>>l[0] = 4
>

2. 两者的成员函数

tuple几乎没什么成员函数,list却有着丰富的成员函数:

>>>t = (1, 2, 3, 3, 4)
>>>dir(t)
# 有意义的成员函数只有`count`、`index`
# count,记录元组中某一元素出现的次数,index返回值所在的下标
>>>t.count(3)
2
>>>t.count(2)
1
>>>t.index(4)
4

>>>l=[1, 2, 3, 4]
dir(l)

3. 彼此间类型转换

>>>l = [1, 2, 3, 3, 4]
>>>tuple(l)
(1, 2, 3, 3, 4)
>>>t = (1, 2, 3, 3, 4)
>>>list(t)
[1, 2, 3, 3, 4]

>>>(l)
[1, 2, 3, 3, 4]
>>>[t]                 # 由元组组成的list
[(1, 2, 3, 3, 4)]

来源:https://blog.csdn.net/iCloudEnd/article/details/99498456

标签:Python,Tuple,append
0
投稿

猜你喜欢

  • asp 关键词高亮显示(不区分大小写)

    2011-04-07 10:55:00
  • python3实现基于用户的协同过滤

    2023-11-17 01:39:47
  • 如何将Python脚本打包成exe应用程序介绍

    2021-12-26 20:42:07
  • django 实现编写控制登录和访问权限控制的中间件方法

    2021-04-26 21:08:53
  • python绘制字符画视频的示例代码

    2023-11-09 16:21:46
  • Python 读取有公式cell的结果内容实例方法

    2021-09-06 21:07:11
  • Python中序列的修改、散列与切片详解

    2022-10-27 14:47:58
  • 如何将服务器端变量转换为客户端的变量?

    2009-12-03 19:54:00
  • 从两个方面讲解SQL Server口令的脆弱性

    2009-01-08 13:40:00
  • 详解Python安装scrapy的正确姿势

    2023-04-04 01:38:14
  • Python3列表删除的三种方式实现

    2021-03-26 17:55:55
  • vitrualBox+ubuntu16.04安装python3.6最新教程及详细步骤

    2021-06-26 05:34:38
  • 胶水语言Python与C/C++的相互调用的实现

    2021-01-16 20:06:49
  • Python shapefile转GeoJson的2种方式实例

    2023-02-20 01:07:52
  • 在ASP.NET 2.0中操作数据之十:使用 GridView和DetailView实现的主/从报表

    2023-07-02 20:22:40
  • pyramid配置session的方法教程

    2021-04-26 09:23:37
  • Oracle 数据库 临时数据的处理方法

    2009-07-02 11:48:00
  • fckeditor编辑器在php中的配置方法

    2023-10-14 14:26:52
  • 论标志的简洁性

    2009-10-27 16:05:00
  • ASP所有的Session变量获取实现代码

    2011-03-11 10:44:00
  • asp之家 网络编程 m.aspxhome.com