📜  高级Python列表方法和技术

📅  最后修改于: 2022-05-13 01:54:26.422000             🧑  作者: Mango

高级Python列表方法和技术

列表就像动态大小的数组,在其他语言中声明(C++ 中的向量和Java中的 ArrayList)。列表不必总是同质的,这使其成为Python中最强大的工具。单个列表可能包含数据类型,如整数、字符串和对象。列表是可变的,因此即使在创建之后也可以更改它们。

列表是Python中最强大的工具之一。他们有很多隐藏的技巧,这使他们非常多才多艺。让我们探索其中一些有用的技术,它们使我们的生活更轻松!!!

排序列表

要按升序或降序对列表进行排序,我们使用具有以下语法的sort()函数:

For ascending order: 
list.sort()
For descending order: 
list.sort(reverse=True)

例子:

Python3
# sorting a list using sort() function
 
my_list = [5, 2, 90, 24, 10]
 
 
# sorting in ascending order it permanently
# changes the order of the list
my_list.sort()
print(my_list)
 
# sorting in descending order it permanently
# changes the order of the list
my_list.sort(reverse=True)
print(my_list)


Python3
# temporary sorting using sorted() method
 
my_list = [5, 2, 90, 24, 10]
 
# ascending order
print(sorted(my_list))
 
# descending order
my_list_2 = sorted(my_list)
print(my_list)


Python3
# reverse a list using reverse()
 
my_list = [5, 2, 90, 24, 10]
 
# reverse
my_list.reverse()
print(my_list)


Python3
# reverse using list comprehension
my_list = [5, 2, 90, 24, 10]
 
# reverse
print(my_list[::-1])


Python3
# removing duplicates from a list using dictionaries
 
my_list_1 = [5, 2, 90, 24, 10, 2, 90, 34]
my_list_2 = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e']
 
# removing duplicates from list 1
my_list_1 = list(dict.fromkeys(my_list_1))
print(my_list_1)
 
# removing duplicates from list 2
my_list_2 = list(dict.fromkeys(my_list_2))
print(my_list_2)


Python3
# filtering with the help of filter() function
# creating a filter function filter all the values less than 20
 
# filter function
def my_filter(n):
    if n > 20:
        return n
 
       
# driver code
if __name__ == "__main__":
    my_list = [5, 2, 90, 24, 10, 2, 95, 36]
    my_filtered_list = list(filter(my_filter, my_list))
    print(my_filtered_list)


Python3
# filtering with the help of list comprehension
my_list = [5, 2, 90, 24, 10, 2, 95, 36]
 
# an elegant way to sort the list
my_list = [item for item in my_list if item > 20]
print(my_list)


Python3
# using map() function to modify the text
def squaring(n):
    return n**2
 
# driver code
if __name__ == "__main__":
    my_list = [5, 2, 90, 24, 10, 2, 95, 36]
 
    my_squared_list = list(map(squaring, my_list))
    print(my_squared_list)


Python3
# the same result can be obtained by a much pythonic approach
# i.e., by using list comprehension
my_list = [5, 2, 90, 24, 10, 2, 95, 36]
 
print([i**2 for i in my_list])


Python3
# combing lists with the help of zip() function
my_list_1 = [5, 2, 90, 24, 10]
my_list_2 = [6, 3, 91, 25, 12]
 
# combined
my_combined_list = list(zip(my_list_1, my_list_2))
print(my_combined_list)


Python3
# to find the most frequent element from the list
my_list = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e']
 
most_frequent_value = max(set(my_list), key=my_list.count)
 
print("The most common element is:", most_frequent_value)


Python3
my_list = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e']
 
# to check whether 'c' is a member of my_list
# returns true if present
print('c' in my_list) 
 
# to check whether 'f' is a member of my_list
# returns false if not present
print('f' in my_list)


Python3
# to flatten a list_of_lists by using list comprehension
list_of_lists = [[1, 2],
                 [3, 4],
                 [5, 6],
                 [7, 8]]
 
# using list comprehension
my_list = [item for List in list_of_lists for item in List]
print(my_list)


输出:

[2, 5, 10, 24, 90]
[90, 24, 10, 5, 2]

要临时更改列表的顺序,请使用sorted()函数和语法:

list.sorted()

蟒蛇3

# temporary sorting using sorted() method
 
my_list = [5, 2, 90, 24, 10]
 
# ascending order
print(sorted(my_list))
 
# descending order
my_list_2 = sorted(my_list)
print(my_list)

输出:

[2, 5, 10, 24, 90]
[5, 2, 90, 24, 10]

反转列表

要反转列表的顺序,我们使用reverse()函数。它的语法是:

list.reverse()

例子:

蟒蛇3

# reverse a list using reverse()
 
my_list = [5, 2, 90, 24, 10]
 
# reverse
my_list.reverse()
print(my_list)

输出:

[10, 24, 90, 2, 5]

或者我们可以应用列表理解来反转列表:

list = list[::-1]

例子:

蟒蛇3

# reverse using list comprehension
my_list = [5, 2, 90, 24, 10]
 
# reverse
print(my_list[::-1])

输出:

[10, 24, 90, 2, 5]

删除重复项

由于Python中的字典不包含重复的键。我们使用dict.fromkeys()函数将我们的列表转换为以列表元素为键的字典。然后我们将字典转换回列表。

这是自动删除所有重复项的强大技巧。它的语法是:

My_list =[‘a’, ’b’, ’c’, ’b’, ’a’]
Mylist = list(dict.fromkeys(My_List))

例子:

蟒蛇3

# removing duplicates from a list using dictionaries
 
my_list_1 = [5, 2, 90, 24, 10, 2, 90, 34]
my_list_2 = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e']
 
# removing duplicates from list 1
my_list_1 = list(dict.fromkeys(my_list_1))
print(my_list_1)
 
# removing duplicates from list 2
my_list_2 = list(dict.fromkeys(my_list_2))
print(my_list_2)

输出:

[5, 2, 90, 24, 10, 34]
['a', 'b', 'c', 'd', 'e']

过滤列表

Python列表可以在filter()函数的帮助下或在列表理解的帮助下进行过滤。下面是语法:

My_list = list(filter(filter_function , iterable_item))

Filter函数返回一个迭代器对象,我们必须将其转换回列表。

例子:

蟒蛇3

# filtering with the help of filter() function
# creating a filter function filter all the values less than 20
 
# filter function
def my_filter(n):
    if n > 20:
        return n
 
       
# driver code
if __name__ == "__main__":
    my_list = [5, 2, 90, 24, 10, 2, 95, 36]
    my_filtered_list = list(filter(my_filter, my_list))
    print(my_filtered_list)

输出:

[90, 24, 95, 36]

我们还可以使用列表理解进行过滤。这是一种更简单和优雅的过滤列表的方法,以下是语法:

My_list = [item for item in my_list if (condition)]

例子:

蟒蛇3

# filtering with the help of list comprehension
my_list = [5, 2, 90, 24, 10, 2, 95, 36]
 
# an elegant way to sort the list
my_list = [item for item in my_list if item > 20]
print(my_list)

输出:

[90, 24, 95, 36]

修改列表

为了在外部函数的帮助下修改列表中的值,我们使用了 map()函数。 Map()函数在将给定函数应用于给定可迭代对象(列表、元组等)的每个元素后返回结果的映射对象(迭代器)。下面是语法:

My_list = list(map(function,iterable))

例子:

蟒蛇3

# using map() function to modify the text
def squaring(n):
    return n**2
 
# driver code
if __name__ == "__main__":
    my_list = [5, 2, 90, 24, 10, 2, 95, 36]
 
    my_squared_list = list(map(squaring, my_list))
    print(my_squared_list)

输出:

[25, 4, 8100, 576, 100, 4, 9025, 1296]

更简洁的方法是使用列表理解。

例子:

蟒蛇3

# the same result can be obtained by a much pythonic approach
# i.e., by using list comprehension
my_list = [5, 2, 90, 24, 10, 2, 95, 36]
 
print([i**2 for i in my_list])

输出:

[25, 4, 8100, 576, 100, 4, 9025, 1296]

组合列表

我们甚至可以在zip()函数的帮助下组合列表,这会产生一个元组列表。这里列表 A 中的每一项都以元组的形式与列表 B 中的相应元素组合在一起。下面是语法:

My_list = zip(list_1, list_2)

例子:

蟒蛇3

# combing lists with the help of zip() function
my_list_1 = [5, 2, 90, 24, 10]
my_list_2 = [6, 3, 91, 25, 12]
 
# combined
my_combined_list = list(zip(my_list_1, my_list_2))
print(my_combined_list)

输出:

[(5, 6), (2, 3), (90, 91), (24, 25), (10, 12)]

查找最常见的项目

为了找到最频繁的元素,我们使用了set()函数。 set()函数从列表中删除所有重复项, max()函数返回最频繁的元素(在“key”的帮助下找到)。关键是一个可选的单参数函数。下面是语法:

Most_frequent_value =max(set(my_list),key=mylist.count)

例子 :

蟒蛇3

# to find the most frequent element from the list
my_list = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e']
 
most_frequent_value = max(set(my_list), key=my_list.count)
 
print("The most common element is:", most_frequent_value)

输出:

The most common element is: a

检查列表中的成员资格

要检查列表中是否存在项目,我们使用in语句。

例子:

蟒蛇3

my_list = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e']
 
# to check whether 'c' is a member of my_list
# returns true if present
print('c' in my_list) 
 
# to check whether 'f' is a member of my_list
# returns false if not present
print('f' in my_list)

输出:

True
False

展平列表列表

有时我们会遇到一个列表,其中每个元素本身都是一个列表。要将列表列表转换为单个列表,我们使用列表理解。

my_list = [item  for List in list_of_lists for item in List ]

例子:

蟒蛇3

# to flatten a list_of_lists by using list comprehension
list_of_lists = [[1, 2],
                 [3, 4],
                 [5, 6],
                 [7, 8]]
 
# using list comprehension
my_list = [item for List in list_of_lists for item in List]
print(my_list)

输出:

[1, 2, 3, 4, 5, 6, 7, 8]