+1MB 2021-11-27 20:34 采纳率: 20%
浏览 11
已结题

三国演义&你不对我队 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]

 

 

  • 写回答

1条回答 默认 最新

  • 晴泪 2022-01-06 19:40
    关注

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

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 2月3日
  • 创建了问题 11月27日

悬赏问题

  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥20 OPENVPN连接问题