三国演义&你不对我队 Ada&贾诩

 

 

1.列表推导式:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:    #选出含有a的字母 
  if "a" in x:
    newlist.append(x)
print(newlist)

['apple', 'banana', 'mango']

还有一种是执行for循环,再执行if判断

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]  #意思是选单词,看符不符合里面有没有a

print(newlist)
newlist = [x for x in range(10) if x < 5]  #选出比5小的数
print(newlist)

[0, 1, 2, 3, 4]

 还有这种,利用离散数学这样理解:

苹果不等于香蕉 1:香蕉不等于香蕉 0:樱桃不等于香蕉 1 ....然后再输出

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x if x != "banana" else "orange" for x in fruits]  
print(newlist)

2.列表排序

区分大小写的排序  sort()

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)
["Kiwi", "Orange","banana", "cherry"]  #

不区分大小写的排序  str.lower

thislist = ["banana","Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)
["banana","cherry","Kiwi","Orange"]

倒序 reverse()

mylist = ["川川一号", "川川二号", "川川三号","川川四号"]
mylist.reverse()
print(mylist)
"川川四号","川川三号","川川二号","川川一号"

3.复制列表

复制列表的副本 copy()

mylist = ["川川一号", "川川二号", "川川三号","川川四号"]
my = mylist.copy()
print(my)
["川川一号", "川川二号", "川川三号","川川四号"]

 制作列表副本:list()

mylist = ["川川一号", "川川二号", "川川三号","川川四号"]
my = list(mylist)
print(my)
["川川一号", "川川二号", "川川三号","川川四号"]

4.加入列表

最简单是 +

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
 ['a', 'b', 'c', 1, 2, 3]

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

for x in list2:
  list1.append(x)

print(list1)
['a', 'b', 'c', 1, 2, 3]

 

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)
['a', 'b', 'c', 1, 2, 3]

 

 

小兄弟,这里是提问区哦,在首页右上角=》创作=》写文章,即可发布自己的文章,祝你好运!