回覆列表
  • 1 # guamf786

    列表、元組、集合、字典相互轉換一、列表元組轉其他1、列表轉集合(去重)list1 = [6, 7, 7, 8, 8, 9]set(list1)# {6, 7, 8, 9}2、兩個列表轉字典list1 = ["key1","key2","key3"]list2 = ["1","2","3"]dict(zip(list1,list2))# {"key1": "1", "key2": "2", "key3": "3"}3、巢狀列表轉字典list3 = [["key1","value1"],["key2","value2"],["key3","value3"]]dict(list3)# {"key1": "value1", "key2": "value2", "key3": "value3"}4、列表、元組轉字串list2 = ["a", "a", "b"]"".join(list2)# "aab"tup1 = ("a", "a", "b")"".join(tup1)# "aab"二、字典轉其他1、 字典轉換為字串dic1 = {"a":1,"b":2}str(dic1)# "{"a": 1, "b": 2}"2、字典key和value互轉dic2 = {"a": 1, "b": 2, "c": 3}{value:key for key, value in a_dict.items()}# {1: "a", 2: "b", 3: "c"}三、字串轉其他1、字串轉列表s = "aabbcc"list(s)# ["a", "a", "b", "b", "c", "c"]2、字串轉元組tuple(s)# ("a", "a", "b", "b", "c", "c")3、 字串轉集合set(s)# {"a", "b", "c"}4、字串轉字典dic2 = eval("{"name":"ljq", "age":24}")5、切分字串a = "a b c"a.split(" ")# ["a", "b", "c"]

  • 中秋節和大豐收的關聯?
  • 如何辨別YY羽毛球拍子的真假?