当前位置:   article > 正文

python学习1 两数之和(建字典)_python两数之和字典

python两数之和字典

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {}  #创建空字典
        for index, num in enumerate(nums):#从前往后,逐个存入字典,让后面的数找到前面的数
            another_num = target - num
            if another_num in hashmap:
                return [hashmap[another_num], index]
            hashmap[num] = index #将num输入字典,建立num:index,这样取数就可以根据num取出下标
        return None
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
enumerate(sequence, [start=0])
  • 1

参数:
1.sequence – 一个序列、迭代器或其他支持迭代对象。
2.start – 下标起始位置。

该函数是枚举列举的意思,同时列出数据下标和数据
如下

  >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
    >>> list(enumerate(seasons))
    [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
    >>> list(enumerate(seasons, start=1))       # 下标从 1 开始
    [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
  • 1
  • 2
  • 3
  • 4
  • 5

注意:该函数枚举时,是按 ” 下标:数据 “ 建立

另外找了一些建立字典的方法
声明:转自CSDN (http://blog.csdn.net/csujiangyu/article/details/45176399)
1.创建空字典

>>> dic = {}
>>> type(dic)
<type 'dict'>
  • 1
  • 2
  • 3

2.直接赋值创建

>>> dic = {'spam':1, 'egg':2, 'bar':3}
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}
  • 1
  • 2
  • 3

3.通过关键字dict和关键字参数创建

>>> dic = dict(spam = 1, egg = 2, bar =3)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}
  • 1
  • 2
  • 3

4.通过二元组列表创建

>>> list = [('spam', 1), ('egg', 2), ('bar', 3)]
>>> dic = dict(list)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}
  • 1
  • 2
  • 3
  • 4

5.dict和zip结合创建

>>> dic = dict(zip('abc', [1, 2, 3]))
>>> dic
{'a': 1, 'c': 3, 'b': 2}
  • 1
  • 2
  • 3

6.通过字典推导式创建

>>> dic = {i:2*i for i in range(3)}
>>> dic
{0: 0, 1: 2, 2: 4}
  • 1
  • 2
  • 3

7.通过dict.fromkeys()创建
通常用来初始化字典, 设置value的默认值

>>> dic = dict.fromkeys(range(3), 'x')
>>> dic
{0: 'x', 1: 'x', 2: 'x'}
  • 1
  • 2
  • 3

8.其他

>>> list = ['x', 1, 'y', 2, 'z', 3]
>>> dic = dict(zip(list[::2], list[1::2]))
>>> dic
{'y': 2, 'x': 1, 'z': 3}
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/57661
推荐阅读
相关标签
  

闽ICP备14008679号