求交集
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
# Get the intersection of two lists using the intersection operator (&)
list_intersection = list(set(list1) & set(list2))
print(list_intersection) # Output: [3, 4]
求并集
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
# Get the union of two lists using the union operator (|)
list_union = list(set(list1) | set(list2))
print(list_union) # Output: [1, 2, 3, 4, 5, 6]
求差集
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5]
# Subtract list2 from list1 using list comprehension
result_list = [x for x in list1 if x not in list2]
print(result_list) # Output: [1, 2]
实参前带*带unpack,解压,形参前带*是pack,打包。
def example_function(a, b, c):
print(a, b, c)
args_list = [1, 2, 3]
example_function(*args_list)# output 1, 2, 3
加*表示接受一个tuple(元组)
def f(*args):
for arg in args: # 取出tuple中的每个元素,然后打印
print(arg)
f(1,2,3,4)
1
2
3
实参前带**,表示传进来的可以看作字典。
def display_info(**details):
for key, value in details.items():
print(f"{key.capitalize()}: {value}")
# Calling the function with various keyword arguments
display_info(name="John", age=25, occupation="Engineer", city="San Francisco")
def f(**kargs):
print(kargs)
f(a=1, b=2)
{'a': 1, 'b': 2}