本文介绍一些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])