列表嵌套展开
lst =[1,[2],[[3]],[[4,[5],6]],7,8,[9]]
def flat(nums):
res = []
for i in nums:
if isinstance(i, list):
res.extend(flat(i))
else:
res.append(i)
return res
new_lst = flat(lst)
print(new_lst)
参考资料
字典互换键值对
三种方式交换键值对(前提:值唯一):
1.
mydict={"a":1,"b":2,"c":3}
mydict_new={}
for key,val in mydict.items():
mydict_new[val]=key
2.
mydict={"a":1,"b":2,"c":3}
mydict_new=dict([val,key] for key,val in mydict.items())
3.利用zip运算符:
mydict={"a":1,"b":2,"c":3}
mydict_new=dict(zip(mydict.values(),mydict.keys()))
参考资料
lambda
twosum
class Solution(object):
def twoSum(self, nums, target):
result = []
for i in range(0,len(nums)):
oneNum = nums[i]
twoNum = target - oneNum
if twoNum in nums:
j = nums.index(twoNum)
if i != j:
result.append(i)
result.append(j)
return result
twosum