
有用的20个python代码段(2):
1、列表解析
在其他列表的基础上,列表解析为创建列表提供一种优雅的方式。
以下代码通过将旧列表的每个对象乘两次,创建一个新的列表。
1 2 3 4 5 | # Multiplying each element in a list by 2
original_list = [1,2,3,4]
new_list = [2*x for x in original_list]
print (new_list)
# [2,4,6,8]
|
2、两个变量之间的交换值
Python可以十分简单地交换两个变量间的值,无需使用第三个变量。
1 2 3 4 5 | a = 1
b = 2
a, b = b, a
print (a) # 2
print (b) # 1
|
3、将字符串拆分成子字符串列表
通过使用.split()方法,可以将字符串分成子字符串列表。还可以将想拆分的分隔符作为参数传递。
1 2 3 4 5 6 7 8 | string_1 = "My name is Chaitanya Baweja"
string_2 = "sample/ string 2"
# default separator ' '
print (string_1.split())
# [ 'My' , 'name' , 'is' , 'Chaitanya' , 'Baweja' ]
# defining separator as '/'
print (string_2.split( '/' ))
# [ 'sample' , ' string 2' ]
|
4、将字符串列表整合成单个字符串
join()方法将字符串列表整合成单个字符串。在下面的例子中,使用comma分隔符将它们分开。
1 2 3 4 5 | list_of_strings = [ 'My' , 'name' , 'is' , 'Chaitanya' , 'Baweja' ]
# Using join with the comma separator
print ( ',' .join(list_of_strings))
# Output
# My,name,is,Chaitanya,Baweja
|
更多Python知识,请关注:Python自学网!!