Python刷题系列(6)_列表List(下)

简介: 列表是一个有序的,可修改的(增删查改),元素以逗号分隔,以中括号包围的序列。

16、从列表中获取唯一值


6c4388232ca64d46bf7fc17cfef7ff58.png78926debe1024ffeb4c305d9e27cce5f.png

my_list = [10, 20, 30, 40, 20, 50, 60, 40]
print("Original List : ",my_list)
my_set = set(my_list)
my_new_list = list(my_set)
print("List of unique numbers : ",my_new_list)
'''
Original List :  [10, 20, 30, 40, 20, 50, 60, 40]
List of unique numbers :  [40, 10, 50, 20, 60, 30]
'''


17、查找列表中第二小的数字


情况一:

aade2f8ece394b7d853b558ed3b68b31.png


情况二:

b4f6794bd21647e3aa86ef412f723035.png4488e55270844e1a88b05231450d98f1.png

分析:需要使用列表和集合,并进行排序,最后找到第二小的数字,如果题目问的是第二大的也是如此

def second_smallest(numbers):
  if (len(numbers)<2):
    return
  if ((len(numbers)==2)  and (numbers[0] == numbers[1]) ):
    return
  dup_items = set()# 空集合
  uniq_items = []# 空列表
  for x in numbers:
    if x not in dup_items:
      uniq_items.append(x)
      dup_items.add(x)
  uniq_items.sort() #将列表中的元素从小到大进行排序   
  return  uniq_items[1]   
print(second_smallest([1, 2, -8, -2, 0, -2]))
print(second_smallest([1, 1, 0, 0, 2, -2, -2]))
print(second_smallest([1, 1, 1, 0, 0, 0, 2, -2, -2]))
print(second_smallest([2,2]))
print(second_smallest([2]))
'''
-2
0
0
None
None
'''


18、将列表拆分成元组


cd3beb884e39445796e250a361940113.pnge756115134a84986898cfba8f831aeac.png

color = [("Black", "#000000", "rgb(0, 0, 0)"), ("Red", "#FF0000", "rgb(255, 0, 0)"),
         ("Yellow", "#FFFF00", "rgb(255, 255, 0)")]
var1, var2, var3 = color
print(var1)
print(var2)
print(var3)
print(type(var1))
'''
('Black', '#000000', 'rgb(0, 0, 0)')
('Red', '#FF0000', 'rgb(255, 0, 0)')
('Yellow', '#FFFF00', 'rgb(255, 255, 0)')
<class 'tuple'>
'''


19、连接列表的元素


f6da231857f54232baf94e8d47547bd4.png

08fd234bc2914e2a995a04165e5a9854.png

color = ['red', 'green', 'orange']
print('-'.join(color))
print(''.join(color))
'''
red-green-orange
redgreenorange
'''

但是color本身是没有变的


20、将字符串转换为列表


import ast
color ="['Red', 'Green', 'White']"
print(ast.literal_eval(color))  #['Red', 'Green', 'White']

4c7cd6efa8824b83b6c21e6b6c5abf52.png


【3】eval

eval 函数在Python中做数据类型的转换还是很有用的。

它的作用就是把数据还原成它本身或者是能够转化成的数据类型。


image.png


由于eval存在安全隐患,因此可以使用literal_eval()函数:

则会判断需要计算的内容计算后是不是合法的python类型,如果是则进行运算,否则就不进行运算。

Python中函数 eval 和 ast.literal_eval 的区别详解


21、从给定列表中删除特定单词


def remove_words(list1, remove_words):
    for word in list(list1):
        if word in remove_words:
            list1.remove(word)
    return list1        
colors = ['red', 'green', 'blue', 'white', 'black', 'orange']
remove_colors = ['white', 'orange']
print("Original list:")
print(colors)
print("\nRemove words:")
print(remove_colors)
print("\nAfter removing the specified words from the said list:")
print(remove_words(colors, remove_colors))
'''
Original list:
['red', 'green', 'blue', 'white', 'black', 'orange']
Remove words:
['white', 'orange']
After removing the specified words from the said list:
['red', 'green', 'blue', 'black']
'''


image.png


22、将字符串和字符列表转换为单个字符列表


def l_strs_to_l_chars(lst):
    result = [i for element in lst for i in element]
    return result
colors = ["red", "white", "a", "b", "black", "f"]
print("Original list:")
print(colors)
print("\nConvert the said list of strings and characters to a single list of characters:")
print(l_strs_to_l_chars(colors))
'''
Original list:
['red', 'white', 'a', 'b', 'black', 'f']
Convert the said list of strings and characters to a single list of characters:
['r', 'e', 'd', 'w', 'h', 'i', 't', 'e', 'a', 'b', 'b', 'l', 'a', 'c', 'k', 'f']
'''

c50df634f0f7443b8df7a6a88cc88a5f.pngee219a5637ae42bca475b546e123ec22.png


23、计算给定列表列表中子列表的最大和最小和



cadd8f9f97af4c89902f08f2d6f67b73.png167452e14bc347b9a8df340237de5d45.png

def max_min_sublist(lst):
    max_result = (max(lst, key=sum))
    min_result = (min(lst, key=sum))
    return max_result,min_result
nums = [[1,2,3,5], [2,3,5,4], [0,5,4,1], [3,7,2,1], [1,2,1,2]]
print("Original list:")
print(nums)
result = max_min_sublist(nums)
print("\nMaximum sum of sub list of the said list of lists:")
print(result[0])
print("\nMinimum sum of sub list of the said list of lists:")
print(result[1])

fb085bb7630540739f26c525491bdd09.png


24、查找给定列表中出现次数最多的项目


5cbc7f5124b241a78b6af5b76729565f.png


c8c3cbfe5334445598053291657f1f49.png

def max_occurrences(nums):
    max_val = 0
    result = nums[0] 
    for i in nums:
        occu = nums.count(i)
        if occu > max_val:
            max_val = occu
            result = i 
    return result
nums = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,4,6,9,1,2]
print ("Original list:")
print(nums)
print("\nItem with maximum occurrences of the said list:")
print(max_occurrences(nums))


25、列表中提取给定数量的随机选择的元素


551e26511d304d188d842c0fc7f85d89.png

使用random.sample

import random
def random_select_nums(n_list, n):
        return random.sample(n_list, n)
n_list = [1,1,2,3,4,4,5,1]
print("Original list:") 
print(n_list)
selec_nums = 3
result = random_select_nums(n_list, selec_nums)
print("\nSelected 3 random numbers of the above list:")
print(result) 


相关文章
|
3天前
|
算法 数据挖掘 数据处理
使用 Python 循环创建多个列表
在Python中,动态创建多个列表对于数据处理和算法实现十分有用。本文介绍了四种方法:1) 列表推导式,如创建偶数和奇数列表;2) 使用循环和`append()`,示例为生成斐波那契数列;3) 结合字典与循环,按条件(如正负数)分组;4) 列表生成器,用于一次性生成多组随机数列表。这些方法有助于提高代码效率和可读性。
14 1
|
6天前
四种解决”Arg list too long”参数列表过长的办法
这些方法都可以帮助你避免因参数列表过长而导致的错误。选择方法取决于具体情况和需求。
10 0
|
10天前
|
Python
python学习-函数模块,数据结构,字符串和列表(下)
python学习-函数模块,数据结构,字符串和列表
53 0
|
10天前
|
索引 容器
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
|
11天前
|
存储 索引 Python
python学习5-列表的创建、增删改查、排序
python学习5-列表的创建、增删改查、排序
|
17天前
|
索引 Python 容器
python 数据类型之列表
python 数据类型之列表
|
18天前
使用Vant框架的组件van-pull-refresh搭配van-list和van-card完成上滑加载更多列表数据,下拉刷新当前列表数据(等同于翻页功能)
使用Vant框架的组件van-pull-refresh搭配van-list和van-card完成上滑加载更多列表数据,下拉刷新当前列表数据(等同于翻页功能)
|
19天前
|
索引 Python
Python标准数据类型-List(列表)
Python标准数据类型-List(列表)
42 1
|
1月前
|
存储 安全 Java
java集合框架及其特点(List、Set、Queue、Map)
java集合框架及其特点(List、Set、Queue、Map)
|
25天前
|
Java
Java使用List去重的四中方式
Java使用List去重的四中方式
19 6