Python:防止double for循环返回列表的相同索引
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python:防止double for循环返回列表的相同索引,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1832字,纯文字阅读大概需要3分钟。
内容图文
![Python:防止double for循环返回列表的相同索引](/upload/InfoBanner/zyjiaocheng/685/c095bb55162849f7b03c9daea945a4b5.jpg)
我目前正在处理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]
.
我当前的代码是:
def twosum_indices(nums, target):
for i in nums:
for v in nums[i + 1:]:
if i + v == target:
return nums.index(i), nums.index(v)
在这种情况下,nums是一个整数列表,并且程序必须在列表中返回两个不同的索引,以使它们的真实值累加到给定的目标中.尽管此方法在大多数测试用例中都可以正常工作,但在像[3,3]这样的两个值都相同的列表上却失败了,并且两次返回相同的索引,例如[0,0],而不是返回实际的[0, 1].为什么会这样呢?
解决方法:
您的代码中存在多个错误,其中最重要的一个错误是未能使用枚举而不是list.index.例如,[3,3] .index(3)当然总是0.
该答案的重点不是寻求最有效的解决方案,而是改进您的特定方法.您也可以看到O(n) solution.
了解列表理解
作为前提,首先要了解multiple for loops can exist in a list comprehension.
def sums(nums):
return [x + y for x in nums for y in nums[:x]]
以上等同于:
def sums(nums):
output = []
for x in nums:
for y in nums[:x]:
output.append(x + y)
return output
使用链生成器表达式的解决方案
def twosum_indices(nums, target):
return next((i, j) for i in range(len(nums)) for j in range(len(nums[:i])) if (nums[i] + nums[j] == target))
例子:
print(sorted(twosum_indices([2, 7, 11, 15], 9)))
[0, 1]
print(sorted(twosum_indices([3, 3], 6)))
[0, 1]
将生成器表达式与itertools结合使用的解决方案
使用itertools有点简单:
import itertools
def twosum_indices_it(nums, target):
return next((i, j) for (i, x), (j, y) in itertools.combinations(enumerate(nums), 2) if (x + y == target))
例子:
print(sorted(twosum_indices_it([2, 7, 11, 15], 9)))
[0, 1]
print(sorted(twosum_indices_it([3, 3], 6)))
[0, 1]
内容总结
以上是互联网集市为您收集整理的Python:防止double for循环返回列表的相同索引全部内容,希望文章能够帮你解决Python:防止double for循环返回列表的相同索引所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。