python基础之 List

本文介绍一些list基础知识

1. 核查列表是否存在某元素

# List of string 
listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from']
  • 使用成员运算符 in / not in
if 'at' in listOfStrings :
    print("Yes, 'at' found in List : " , listOfStrings)
-----------------------------------------------------------
if 'time' not in listOfStrings :
    print("Yes, 'time' NOT found in List : " , listOfStrings)
  • 使用list.count()函数
if listOfStrings.count('at') > 0 :
    print("Yes, 'at' found in List : " , listOfStrings)
基于自定义逻辑核查列表中是否存在某元素
  • 使用 any() 函数
result = any(len(elem) == 5 for elem in listOfStrings)
 
if result:
    print("Yes, string element with size 5 found")

在这里插入图片描述

2. 核查列表1是否包含列表2中的所有元素

假设存在如下两个列表:

# List of string 
list1 = ['Hi' ,  'hello', 'at', 'this', 'there', 'from']
 
# List of string
list2 = ['there' , 'hello', 'Hi']
  • 使用 all() 函数
result =  all(elem in list1  for elem in list2)
 
if result:
    print("Yes, list1 contains all elements in list2")    
else:
    print("No, list1 does not contains all elements in list2")
  • 使用 any() 函数
result =  any(elem in list1  for elem in list2)
 
if result:
    print("Yes, list1 contains any elements of list2")    
else :
    print("No, list1 contains any elements of list2")

在这里插入图片描述

3. 创建列表,并用相同的值进行初始化

  • 使用 *
listOfStrings1 = ['Hi'] * 10
  • 使用列表推导式
listOfStrings2 = ['Hi' for i in range(10)]

在这里插入图片描述

4. 如何迭代一个列表?

创建如下列表

wordList = ['Hi' , 'hello', 'at', 'this', 'there', 'from']
  • 使用 for-in 循环
for word in wordList:
    print(word)
  • 使用while循环
i = 0
sizeofList = len(wordList) 
while i < sizeofList :
    print(wordList[i]) 
    i += 1
  • 使用 for + range()
for  i in range(len(wordList)) :
    print(wordList[i])
  • 使用列表推导式
[print(i) for i in wordList]

在这里插入图片描述

5. 在指定位置插入元素

初始列表如下:

# List of string 
list1 = ['Hi' ,  'hello', 'at', 'this', 'there', 'from']
  • 索引3位置插入
list1.insert(3, 'why')
  • 列表开始位置插入
list1.insert(0, 'city')
  • 列表指定位置插入列表
list1 = ['city', 'Hi', 'hello', 'at', 'why', 'this', 'there', 'from']
 
list2 = [3,5,7,1]
  • 使用 for 循环
for elem in reversed(list2) :
    list1.insert(3, elem)
  • 使用列表切换进行拼接
list1 = list1[:3] + list2 + list1[3:]

在这里插入图片描述

6. 基于列表中元组的第二个元素进行排序

初始列表如下,由若干元素构成:

wordFreq = [ ('the' , 34) , ('at' , 23), ('should' , 1) , ('from' , 3) ]
  • sort() 函数默认按照元组的第一个元素进行排序
wordFreq.sort()
  • 使用 lambda 函数对列表中元组的第二个元素进行排序
wordFreq.sort(key=lambda elem: elem[1])

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值