給定一個整數數組和一個目標值,找出數組中和爲目標值的兩個數。你能夠假設每一個輸入只對應一種答案,且一樣的元素不能被重複利用。示例:給定nums = [2,7,11,15],target=9 由於 nums[0]+nums[1] = 2+7 =9,因此返回[0,1]python
class Solution: def twoSum(self,nums,target): """ :type nums: List[int] :type target: int :rtype: List[int] """ d = {} size = 0 while size < len(nums): if target-nums[size] in d: if d[target-nums[size]] <size: return [d[target-nums[size]],size] else: d[nums[size]] = size size = size +1 solution = Solution() list = [2,7,11,15] target = 9 nums = solution.twoSum(list,target) print(nums)
給列表中的字典排序:假設有以下list對象,alist=[{"name":"a","age":20},{"name":"b","age":30},{"name":"c","age":25}],將alist中的元素按照age從大到小排序
alist=[{"name":"a","age":20},{"name":"b","age":30},{"name":"c","age":25}]
alist_sort = sorted(alist,key=lambda e: e.__getitem__('age'),reverse=True)
def distFunc1(a): """使用集合去重""" a = list(set(a)) print(a) def distFunc2(a): """將一個列表的數據取出放到另外一個列表中,中間做判斷""" list = [] for i in a: if i not in list: list.append(i) #若是須要排序的話用sort list.sort() print(list) def distFunc3(a): """使用字典""" b = {} b = b.fromkeys(a) c = list(b.keys()) print(c) if __name__ == "__main__": a = [1,2,4,2,4,5,7,10,5,5,7,8,9,0,3] distFunc1(a) distFunc2(a) distFunc3(a)
import re # 方法一 def test(filepath): distone = {} with open(filepath) as f: for line in f: line = re.sub("\W+", " ", line) lineone = line.split() for keyone in lineone: if not distone.get(keyone): distone[keyone] = 1 else: distone[keyone] += 1 num_ten = sorted(distone.items(), key=lambda x:x[1], reverse=True)[:10] num_ten =[x[0] for x in num_ten] return num_ten # 方法二 # 使用 built-in 的 Counter 裏面的 most_common import re from collections import Counter def test2(filepath): with open(filepath) as f: return list(map(lambda c: c[0], Counter(re.sub("\W+", " ", f.read()).split()).most_common(10)))