Table of contents
②Use in combination with for function, if function, and split function
2. Convert the list to a tuple
1. Convert tuples to lists
(1) Syntax: list(tuple)
(2) Examples
①Simple usage example
#list
tup1 = (1,4,6,7)
ls1 = list(tup1)
print('转换的列表ls1为:',ls1)
tup2 = ('hello','world','funny','window')
ls2 = list(tup2)
print('转换的列表ls2为:',ls2)
The output is:
转换的列表ls1为: [1, 4, 6, 7]
转换的列表ls2为: ['hello', 'world', 'funny', 'window']
②Use in combination with for function, if function, and split function
ls = {('hello','home','funny','windows','water'), 'come on friends'}
for element in ls:
if type(element) == tuple:
ls1 = list(element)
print('转换的列表ls为:',ls1)
elif type(element) == str:
ls2 = element.split()
print('转换的列表ls为:',ls2)
else:
pass
Output result:
转换的列表ls为: ['hello', 'home', 'funny', 'windows', 'water']
转换的列表ls为: ['come', 'on', 'friends']
illustrate:
① Convert a string to a list type: list = string.split()
②The type function is used to determine what data type the object is.
2. Convert the list to a tuple
(1) Syntax: tuple(list)
(2) Examples
#tuple
#简单的用法实例
ls1 = [1,3,8,6,12,7]
tup1 = tuple(ls1)
print('转换的元组tup1为:',tup1)
ls2 = ['hello','world','funny','window']
tup2 = tuple(ls2)
print('转换的元组tup2为:',tup2)
#与if函数结合使用
ls3 = ['fine','happy','creative']
if type(ls3) == list:
tup3 = tuple(ls3)
print('转换的元组tup3为:',tup3)
else:
pass
The output is:
转换的元组tup1为: (1, 3, 8, 6, 12, 7)
转换的元组tup2为: ('hello', 'world', 'funny', 'window')
转换的元组tup3为: ('fine', 'happy', 'creative')
3. Convert numbers to strings
(1) Syntax: string(number)
(2) Examples
#string
#简单的用法实例
num1 = 543563
string1 = str(num1)
print('转换的字符串string1为:',string1)
print('转换的字符串string1类型为:',type(string1))
num2 = 100086
string2 = str(num2)
print('转换的字符串string2为:',string2)
print('转换的字符串string2类型为:',type(string2))
#与if函数结合使用
ls = [56340,5983.25,'hello',10086,'happy']
n = 2
for i in ls :
if type(i) == int or type(i) == float:
n+=1
string3 = str(i)
print('转换的字符串string%d为:%s'%(n,string3))
print('转换的字符串string%d类型为:%s'%(n,type(string3)))
else:
pass
Output result:
转换的字符串string1为: 543563
转换的字符串string1类型为: <class 'str'>
转换的字符串string2为: 100086
转换的字符串string2类型为: <class 'str'>
转换的字符串string3为:56340
转换的字符串string3类型为:<class 'str'>
转换的字符串string4为:5983.25
转换的字符串string4类型为:<class 'str'>
转换的字符串string5为:10086
转换的字符串string5类型为:<class 'str'>
reference article
For details, please refer to the usage example of the split function: How to split a string in python - the usage and examples of the split function
For specific usage of if judgment statement, please refer to: Usage and examples of python's if conditional statement
For the usage of the specific for function, please refer to:
The usage and examples of python's for loop statement - Programmer Sought