您的位置:首页 > 编程语言 > Python开发

python enumerate()函数

2017-10-30 20:50 260 查看
参考:

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
>>>
0 这
1 是
2 一个
3 测试


# enumerate 还可以接收第二个参数,用于指定索引起始值,如:
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1, 1):
print index, item
>>>
1 这
2 是
3 一个
4 测试


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

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


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

可以利用enumerate():

count = 0
for index, line in enumerate(open(filepath,'r')):
count += 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: