99个Python单行神技,惊艳你的编程世界

打印系统主机名:

import socket; print(socket.gethostname())

解码十六进制字符串:

hex_string = "48656c6c6f20576f726c64"
decoded_string = bytearray.fromhex(hex_string).decode()
print(decoded_string)

解码十六进制字符串:

hex_string = "48656c6c6f20576f726c64"
decoded_string = bytearray.fromhex(hex_string).decode()
print(decoded_string)

从文件中读取行:

with open('file.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())

生成随机整数列表:

import random; random_int_list = [random.randint(1, 100) for _ in range(10)]; print(random_int_list)

计算列表中所有元素的和:

num_list = [1, 2, 3, 4, 5]; total_sum = sum(num_list); print(total_sum)

使用列表推导式过滤奇数

num_list = [1, 2, 3, 4, 5]; odd_numbers = [x for x in num_list if x % 2 != 0]; print(odd_numbers)

将字符串列表连接为单个字符串

str_list = ["Hello", "World", "!"]; combined_str = ' '.join(str_list); print(combined_str)

使用Lambda函数对列表进行排序

num_list = [3, 1, 4, 1, 5, 9, 2]; sorted_list = sorted(num_list, key=lambda x: x); print(sorted_list)

统计列表中每个元素的出现次数

from collections import Counter
num_list = [1, 2, 2, 3, 1, 2, 4]
element_count = Counter(num_list)
print(element_count)

使用Map函数将列表中的元素转为字符串

num_list = [1, 2, 3, 4, 5]; str_list = list(map(str, num_list)); print(str_list)

查找列表中的最大值和最小值

num_list = [10, 5, 20, 3, 15]; max_val = max(num_list); min_val = min(num_list); print(f"Max: {max_val}, Min: {min_val}")

简化if-else条件表达式

value = 10; result = "Even" if value % 2 == 0 else "Odd"; print(result)

使用zip函数合并两个列表

list1 = [1, 2, 3]; list2 = ['a', 'b', 'c']; merged_list = list(zip(list1, list2)); print(merged_list)

查找字符串中某个子字符串的位置

main_string = "Hello, World!"; sub_string = "World"; position = main_string.find(sub_string); print(position)

字典推导式创建字典

keys = ['a', 'b', 'c']; values = [1, 2, 3]; dict_data = {k: v for k, v in zip(keys, values)}; print(dict_data)

使用三元运算符进行简单的条件赋值

x = 5; y = 10; result = x if x > y else y; print(result)

将列表中大于5的元素加倍

num_list = [2, 6, 8, 4, 10]; doubled_list = [x * 2 if x > 5 else x for x in num_list]; print(doubled_list)

使用enumerate函数遍历列表并获取索引和元素

fruits = ['apple', 'banana', 'cherry']; indexed_fruits = list(enumerate(fruits)); print(indexed_fruits)

将字典按值排序并返回新的有序字典

my_dict = {'a': 4, 'b': 2, 'c': 1, 'd': 3}; sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1])}; print(sorted_dict)

使用join方法将列表中的字符串连接为一个长字符串

str_list = ['Hello', 'World', '!']; combined_str = ' '.join(str_list); print(combined_str)

判断是否所有元素都满足某个条件

num_list = [2, 4, 6, 8]; all_even = all(x % 2 == 0 for x in num_list); print(all_even)

使用filter函数筛选出列表中的偶数

num_list = [1, 2, 3, 4, 5, 6]; even_numbers = list(filter(lambda x: x % 2 == 0, num_list)); print(even_numbers)

将字符串转换为小写并去除首尾空格

input_str = "   Hello, World!   "; modified_str = input_str.strip().lower(); print(modified_str)

计算列表中大于5的元素的平均值

num_list = [2, 7, 9, 4, 11]; filtered_nums = [x for x in num_list if x > 5]; avg_value = sum(filtered_nums) / len(filtered_nums); print(avg_value)

使用列表推导式创建一个新列表,其中包含原始列表中每个元素的平方

num_list = [1, 2, 3, 4, 5]; squared_list = [x**2 for x in num_list]; print(squared_list)

将字符串逆序输出

input_str = "Hello, World!"; reversed_str = input_str[::-1]; print(reversed_str)

判断字符串是否是数字

input_str = "12345"; is_numeric = input_str.isnumeric(); print(is_numeric)
  • 单行代码在Python中通常用于执行简单而紧凑的操作,提供了一种便捷的方式来表达某些功能.以下是关于单行代码的作用、功能以及适用场景的总结:

作用和功能:

  1. 执行简单的计算或操作,如数学运算、字符串处理等.
  2. 快速实现特定功能,例如列表推导式、Lambda函数等.
  3. 方便的数据处理和转换,包括读写文件、解析数据等.
  4. 进行条件判断和逻辑处理,简化if-else语句.
  5. 快速生成随机数据、合并数据结构等.

适用场景:

6. 数据处理:快速进行数据处理和转换,如过滤、筛选、转换数据等.

7. 简洁性要求高:在需要保持代码简洁性和可读性的情况下,使用单行代码可以减少代码量.

8. 时间效率要求高:对于简单且耗时较短的操作,单行代码可以提高执行效率.

9. 脚本编写:编写小型脚本或快速原型验证时,单行代码非常方便.