python enumerate()函数

参考:
http://blog.csdn.net/churximi/article/details/51648388

leetcode 1

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

CODE

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i, first in enumerate(nums):#厉害极了!!
            second = target - first
            if second in nums[i+1:]:#妙极了!!!
                i2 = nums[i+1:].index(second) + i + 1
                #nums.index()!!这都可以
                return [i, i2]

enumerate()说明:
1 是python的内置函数
2 在字典上是枚举、列举的意思
3 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
4 多用于在for循环中得到计数

#如果对一个列表,既要遍历索引又要遍历元素时,首先可以这样写:
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1):
    print index, item
>>>
012 一个
3 测试
# enumerate 还可以接收第二个参数,用于指定索引起始值,如:
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1, 1):
    print index, item
>>>
123 一个
4 测试

如果要统计文件的行数,可以这样写:

count = len(open(filepath, 'r').readlines())

这种方法简单,但是可能比较慢,当文件比较大时甚至不能工作。

可以利用enumerate():

count = 0
for index, line in enumerate(open(filepath,'r')): 
    count += 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值