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) 


相关文章
|
1月前
|
索引 Python
Python列表
Python列表。
50 8
|
1月前
|
C语言 Python
[oeasy]python054_python有哪些关键字_keyword_list_列表_reserved_words
本文介绍了Python的关键字列表及其使用规则。通过回顾`hello world`示例,解释了Python中的标识符命名规则,并探讨了关键字如`if`、`for`、`in`等不能作为变量名的原因。最后,通过`import keyword`和`print(keyword.kwlist)`展示了Python的所有关键字,并总结了关键字不能用作标识符的规则。
38 9
|
1月前
|
数据挖掘 大数据 数据处理
python--列表list切分(超详细)
通过这些思维导图和分析说明表,您可以更直观地理解Python列表切分的概念、用法和实际应用。希望本文能帮助您更高效地使用Python进行数据处理和分析。
69 14
|
1月前
|
数据挖掘 大数据 数据处理
python--列表list切分(超详细)
通过这些思维导图和分析说明表,您可以更直观地理解Python列表切分的概念、用法和实际应用。希望本文能帮助您更高效地使用Python进行数据处理和分析。
103 10
|
7月前
|
安全 Java
java线程之List集合并发安全问题及解决方案
java线程之List集合并发安全问题及解决方案
1099 1
|
6月前
|
Java API Apache
怎么在在 Java 中对List进行分区
本文介绍了如何将列表拆分为给定大小的子列表。尽管标准Java集合API未直接支持此功能,但Guava和Apache Commons Collections提供了相关API。
|
6月前
|
运维 关系型数据库 Java
PolarDB产品使用问题之使用List或Range分区表时,Java代码是否需要进行改动
PolarDB产品使用合集涵盖了从创建与管理、数据管理、性能优化与诊断、安全与合规到生态与集成、运维与支持等全方位的功能和服务,旨在帮助企业轻松构建高可用、高性能且易于管理的数据库环境,满足不同业务场景的需求。用户可以通过阿里云控制台、API、SDK等方式便捷地使用这些功能,实现数据库的高效运维与持续优化。
|
6月前
|
存储 安全 Java
详解Java中集合的List接口实现的ArrayList方法 | Set接口实现的HashSet方法
详解Java中集合的List接口实现的ArrayList方法 | Set接口实现的HashSet方法
|
7月前
|
Java API
使用 Java 来实现两个 List 的差集操作
使用 Java 来实现两个 List 的差集操作
264 3
|
6月前
|
存储 Java 索引
Java List接口实现原理与性能评估
Java List接口实现原理与性能评估

热门文章

最新文章