日常被虐
Posted iyouyue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了日常被虐相关的知识,希望对你有一定的参考价值。
列表嵌套展开
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()))
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
以上是关于日常被虐的主要内容,如果未能解决你的问题,请参考以下文章