列表求交并差、形参前带*、形参前带**

求交集

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}

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值