可以对重复的项目使用`.index`吗?

huangapple go评论56阅读模式
英文:

is it possible to .index a repeated item?

问题

mylist中索引第二个7,你可以使用以下代码:

second_seven_index = mylist.index(7, mylist.index(7) + 1)

这将返回第二个7的索引位置。如果要在spy_game函数中修改代码以检查是否包含007,可以使用以下代码:

def spy_game(nums):
    zeros = []
    for num in nums:
        if num == 0:
            zeros.append(num)
        elif num == 7 and len(zeros) >= 2:
            return True
    return False

这个函数将检查列表中是否按顺序包含至少两个0和一个7,如果是则返回True,否则返回False。

英文:

Is it possible to .index a repeated item? for example in mylist=[1,2,7,8,7,12] how can I .index the second 7?

mylist.index(7) just gives me the place of the first seven.
How can i get the placenumber of the second seven?

#### SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order

     spy_game([1,2,4,0,0,7,5]) --> True
     spy_game([1,0,2,4,0,5,7]) --> True
     spy_game([1,7,2,0,4,5,0]) --> False
def spy_game(nums):    ####this only work when the second 0 not in after the 7
    
    while 0 in nums and 7 in nums and nums.count(0)>=2:
        if nums.index(7)>nums.index(0):
            return True 
        else:
            return False
    else:
        return False

答案1

得分: 1

你可以从输入列表中只使用0和7构建一个字符串,然后可以在该字符串中搜索'007'。

像这样:

def spy_game(n: list[int]) -> bool:
    return '007' in ''.join(map(str, (v for v in n if v in {0, 7})))

print(spy_game([1,2,4,0,0,7,5]))
print(spy_game([1,0,2,4,0,5,7]))
print(spy_game([1,7,2,0,4,5,0]))

输出:

True
True
False

选项:

如果你不想构建字符串,可以像下面这样使用整数:

def spy_game(n: list[int]) -> bool:
    jb = (0, 0, 7)
    t = [v for v in n if v in {0, 7}]
    for _t in zip(t, t[1:], t[2:]):
        if _t == jb:
            return True
    return False
英文:

You can construct a string using only 0s and 7s from the input list then you can just search for '007' in that string.

Like this:

def spy_game(n: list[int]) -> bool:
    return '007' in ''.join(map(str, (v for v in n if v in {0, 7})))

print(spy_game([1,2,4,0,0,7,5]))
print(spy_game([1,0,2,4,0,5,7]))
print(spy_game([1,7,2,0,4,5,0]))

Output:

True
True
False

Option:

If you don't want to build strings then just use the integers as follows:

def spy_game(n: list[int]) -> bool:
    jb = (0, 0, 7)
    t = [v for v in n if v in {0, 7}]
    for _t in zip(t, t[1:], t[2:]):
        if _t == jb:
            return True
    return False

答案2

得分: 0

以下是翻译好的代码部分:

用切片的方式来实现

a = [0, 0, 7, 1, 5, 6]
b = [0, 7, 0, 1, 5, 6, 7, 5, ]
c = [7, 0, 0, 1, 4, 5, 6]
d = [0, 7, 0, 7]

def spy_game(l: list[int]) -> bool:
    try:
        ind1 = l.index(0)
        ind2 = l[ind1 + 1:].index(0)
        ind3 = l[ind1 + ind2 + 1:].index(7)  # 可以替换为 if 7 in l[ind1+ind2:]
        return True
    except ValueError:
        return False

print(spy_game(a))
print(spy_game(b))
print(spy_game(c))
print(spy_game(d))

请注意如果值在列表中不存在.index 将引发 ValueError 异常
英文:

The way I would do it with slicing:

a = [0, 0, 7, 1, 5, 6]
b = [0, 7, 0, 1, 5, 6, 7, 5, ]
c = [7, 0, 0, 1, 4, 5, 6]
d = [0, 7, 0, 7]


def spy_game(l: list[int]) -> bool:
    try:
        ind1 = l.index(0)
        ind2 = l[ind1 + 1:].index(0)
        ind3 = l[ind1 + ind2 + 1:].index(7)  # can replace with if 7 in l[ind1+ind2:]
        return True
    except ValueError:
        return False


print(spy_game(a))
print(spy_game(b))
print(spy_game(c))
print(spy_game(d))

notice that if the value doesn't exist in the list .index will raise a ValueError

答案3

得分: -1

根据已有的评论建议,有更简单的方法可以做到这一点。但是,对于你的具体问题,你可以使用:

mylist = [1, 2, 7, 8, 7, 12]
[i for i, x in enumerate(mylist) if x == 7]

通过使用一个列表生成器遍历mylist中的索引和项对,你可以检查项是否等于7,如果是的话,保存该项的索引。

英文:

As the comments already suggest, there are easier ways to do so. However, for your specific question, you could use:

mylist=[1,2,7,8,7,12]
[i for i,x in enumerate(mylist) if x == 7]
>>> [2,4]

By using a list generator looping over the pairs (index, item) in mylist, you can check whether the item is equal to 7, and if so, save the index of that item.

huangapple
  • 本文由 发表于 2023年7月17日 19:49:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76704152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定