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) 


相关文章
|
2月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
178 1
|
2月前
|
开发者 Python
Python列表推导式:优雅与效率的完美结合
Python列表推导式:优雅与效率的完美结合
391 116
|
2月前
|
Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
413 119
|
2月前
|
Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
|
2月前
|
索引 Python
Python 列表切片赋值教程:掌握 “移花接木” 式列表修改技巧
本文通过生动的“嫁接”比喻,讲解Python列表切片赋值操作。切片可修改原列表内容,实现头部、尾部或中间元素替换,支持不等长赋值,灵活实现列表结构更新。
122 1
|
2月前
|
大数据 开发者 Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
|
2月前
|
存储 Java 索引
(Python基础)新时代语言!一起学习Python吧!(二):字符编码由来;Python字符串、字符串格式化;list集合和tuple元组区别
字符编码 我们要清楚,计算机最开始的表达都是由二进制而来 我们要想通过二进制来表示我们熟知的字符看看以下的变化 例如: 1 的二进制编码为 0000 0001 我们通过A这个字符,让其在计算机内部存储(现如今,A 字符在地址通常表示为65) 现在拿A举例: 在计算机内部 A字符,它本身表示为 65这个数,在计算机底层会转为二进制码 也意味着A字符在底层表示为 1000001 通过这样的字符表示进行转换,逐步发展为拥有127个字符的编码存储到计算机中,这个编码表也被称为ASCII编码。 但随时代变迁,ASCII编码逐渐暴露短板,全球有上百种语言,光是ASCII编码并不能够满足需求
160 4
|
9月前
|
存储 人工智能 索引
Python数据结构:列表、元组、字典、集合
Python 中的列表、元组、字典和集合是常用数据结构。列表(List)是有序可变集合,支持增删改查操作;元组(Tuple)与列表类似但不可变,适合存储固定数据;字典(Dictionary)以键值对形式存储,无序可变,便于快速查找和修改;集合(Set)为无序不重复集合,支持高效集合运算如并集、交集等。根据需求选择合适的数据结构,可提升代码效率与可读性。
|
10月前
|
安全 数据处理 索引
深入探讨 Python 列表与元组:操作技巧、性能特性与适用场景
Python 列表和元组是两种强大且常用的数据结构,各自具有独特的特性和适用场景。通过对它们的深入理解和熟练应用,可以显著提高编程效率和代码质量。无论是在数据处理、函数参数传递还是多线程环境中,合理选择和使用列表与元组都能够使得代码更加简洁、高效和安全。
260 9
|
存储 索引 Python
Python学习笔记----列表、元组和字典的基础操作
这篇文章是一份Python学习笔记,涵盖了列表、元组和字典的基础操作,包括它们的创建、修改、删除、内置函数和方法等。
Python学习笔记----列表、元组和字典的基础操作

推荐镜像

更多