Python常见数据类型转换操作示例

yipeiwu_com7年前Python基础

本文实例讲述了Python常见数据类型转换操作。分享给大家供大家参考,具体如下:

类型转换

主要针对几种存储工具:list、tuple、dict、set

特殊之处:dict是用来存储键值对的。

1、list 转换为set

l1 = [1, 2, 4, 5]
s1 = set(l1)
print(type(s1))
print(s1)

输出:

<class 'set'>
{1, 2, 4, 5}

2、set转换为list

s1 = set([1, 2, 3, 4])
l1 = list(s1)
print(type(l1))
print(l1)

输出:

<class 'list'>
[1, 2, 3, 4]

3、tuple 转换为set

t1 = (1, 2, 3, 4)
s1 = set(t1)
print(type(s1))
print(s1)

输出:

<class 'set'>
{1, 2, 3, 4}

4、set转换为tuple

s1 = set([1, 2, 3, 4])
t1 = tuple(s1)
print(type(t1))
print(t1)

输出:

<class 'tuple'>
(1, 2, 3, 4)

5、list转tuple

l1 = [1, 2, 4, 5]
t1 = tuple(l1)
print(type(t1))
print(t1)

输出:

<class 'tuple'>
(1, 2, 4, 5)

6、tuple转list

t1 = (1, 2, 3, 4)
l1 = list(t1)
print(type(l1))
print(l1)

输出:

<class 'list'>
[1, 2, 3, 4]

7、list转dict

list1=[('a',1),('b',2),('c',3)]
dict1={k:v for k,v in list1}
dict2={v:k for k,v in list1}
print(dict1)
print(dict2)

输出:

{'a': 1, 'b': 2, 'c': 3}
{1: 'a', 2: 'b', 3: 'c'}

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

用Python编写一个简单的Lisp解释器的教程

用Python编写一个简单的Lisp解释器的教程

本文有两个目的: 一是讲述实现计算机语言解释器的通用方法,另外一点,着重展示如何使用Python来实现Lisp方言Scheme的一个子集。我将我的解释器称之为Lispy (lis.py)...

python字符串过滤性能比较5种方法

python字符串过滤性能比较5种方法比较 总共比较5种方法。直接看代码: import random import time import os import string ba...

Python实现的绘制三维双螺旋线图形功能示例

Python实现的绘制三维双螺旋线图形功能示例

本文实例讲述了Python实现的绘制三维双螺旋线图形功能。分享给大家供大家参考,具体如下: 代码: # -*- coding:utf-8 -*- #! python3 #绘制三维双螺...

简单讲解Python编程中namedtuple类的用法

Python的Collections模块提供了不少好用的数据容器类型,其中一个精品当属namedtuple。 namedtuple能够用来创建类似于元祖的数据类型,除了能够用索引来访问数...

PyCharm设置护眼背景色的方法

PyCharm设置护眼背景色的方法

方法一: File->Seting->Editor-Colors->General->Text->Default text->BackGround设置...