1. 如何将一个列表中的元素随机排序?
import random

my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)
  1. 如何检查一个字符串是否是回文?
def is_palindrome(s):
    return s == s[::-1]

print(is_palindrome('racecar'))
print(is_palindrome('hello'))
  1. 如何计算一个字符串中每个字符出现的次数?
from collections import Counter

string = 'hello world'
count = Counter(string)
print(count)
  1. 如何取出一个列表中出现次数最多的元素?
from collections import Counter

my_list = [1, 2, 3, 4, 5, 2, 3, 2, 2]
count = Counter(my_list)
print(count.most_common(1)[0][0])
  1. 如何将一个字符串中的所有单词首字母大写?
string = 'hello world'
new_string = ' '.join([word.capitalize() for word in string.split()])
print(new_string)
  1. 如何从一个列表中随机取出一个元素?
import random

my_list = [1, 2, 3, 4, 5]
random_element = random.choice(my_list)
print(random_element)
  1. 如何将一个列表中的所有元素都变成字符串类型?
my_list = [1, 2, 3, 4, 5]
new_list = [str(element) for element in my_list]
print(new_list)
  1. 如何将一个字符串中的所有数字提取出来?
import re

string = 'hello 123 world 456'
numbers = re.findall('\d+', string)
print(numbers)
  1. 如何找到一个列表中第二大的元素?
my_list = [1, 2, 3, 4, 5]
new_list = sorted(set(my_list))
print(new_list[-2])
  1. 如何将一个列表中的所有元素去重?
my_list = [1, 2, 3, 4, 5, 2, 3, 2, 2]
new_list = list(set(my_list))
print(new_list)
  1. 如何将一个列表中的所有元素向左移动n位?
my_list = [1, 2, 3, 4, 5]
n = 2
new_list = my_list[n:] + my_list[:n]
print(new_list)
  1. 如何将一个列表中的所有元素向右移动n位?
my_list = [1, 2, 3, 4, 5]
n = 2
new_list = my_list[-n:] + my_list[:-n]
print(new_list)
  1. 如何找到两个列表中的共同元素?
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
common_elements = list(set(list1) & set(list2))
print(common_elements)
  1. 如何将一个字符串中的所有单词反转?
string = 'hello world'
new_string = ' '.join([word[::-1] for word in string.split()])
print(new_string)
  1. 如何找到一个字符串中最长的单词?
string = 'hello world this is a test'
longest_word = max(string.split(), key=len)
print(longest_word)
  1. 如何找到一个字符串中所有的URL?
import re

string = 'hello, this is a url http://www.google.com and this is another url https://www.facebook.com'
urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', string)
print(urls)
  1. 如何将一个列表中的元素按照长度排序?
my_list = ['hello', 'world', 'this', 'is', 'a', 'test']
new_list = sorted(my_list, key=len)
print(new_list)
  1. 如何将一个列表中的元素按照最后一个字符排序?
my_list = ['hello', 'world', 'this', 'is', 'a', 'test']
new_list = sorted(my_list, key=lambda x: x[-1])
print(new_list)
  1. 如何将一个字典按照value从大到小排序?
my_dict = {'a': 5, 'b': 2, 'c': 7, 'd': 1}
new_dict = dict(sorted(my_dict.items(), key=lambda x: x[1], reverse=True))
print(new_dict)
  1. 如何将一个二维列表转换成一维列表?
my_list = [[1, 2], [3, 4], [5, 6]]
new_list = [element for sublist in my_list for element in sublist]
print(new_list)
20个有难度的python题目和答案

原文地址: https://www.cveoy.top/t/topic/bL5E 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录