python 50 one line code

发布于:2023-10-25 ⋅ 阅读:(90) ⋅ 点赞:(0)

1. “Hello, World!” in Python

print("Hello, World!")

2. Swap two variables without a temporary variable

a, b = b, a

3. Find the maximum element in a list

max_element = max(my_list)

4. List comprehension to square each element in a list

squared_list = [x**2 for x in my_list]

5. Check if a string contains a substring

contains_substring = 'substring' in my_string

6. Reverse a string

reversed_string = my_string[::-1]

7. Get the length of a list

length = len(my_list)

8. Sort a list in-place

my_list.sort()

9. Get the unique elements in a list

unique_elements = list(set(my_list))

10. Create a dictionary with a comprehension

my_dict = {
   key: value for key, value in zip(keys, values)}

11. Read a file in one line

content = open('file.txt').read()

12. Count occurrences of an element in a list

count = my_list.count(element)

13. Check if a list is empty

is_empty = not bool(my_list)

14. Calculate the sum of a list

total = sum(my_list)

15. Get the first element of a list (or a default value)

first_element = my_list[0
本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到