python enumerate()函数
2017-10-30 20:50
260 查看
参考:
http://blog.csdn.net/churximi/article/details/51648388
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
CODE
enumerate()说明:
1 是python的内置函数
2 在字典上是枚举、列举的意思
3 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
4 多用于在for循环中得到计数
如果要统计文件的行数,可以这样写:
这种方法简单,但是可能比较慢,当文件比较大时甚至不能工作。
可以利用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 >>> 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
相关文章推荐
- python之函数enumerate()
- python进阶教程之循环相关函数range、enumerate、zip
- Python enumerate() 函数
- python之enumerate()函数的探究
- python中列表 字典 元祖 enumerate()函数
- python之函数enumerate()
- Python函数-enumerate()
- python中的enumerate()函数
- python 函数 —— enumerate()
- python的enumerate()函数
- Python enumerate() 函数
- Python enumerate() 函数
- Python中enumerate()函数的用法
- python的enumerate()函数
- Python学习——enumerate()函数的用法
- Python---高级函数map, filter, zip, enumerate等的用法
- python的enumerate()函数
- python中enumerate 函数
- python之enumerate()函数
- python中的函数:zip ,map,enumerate