相关疑难解决方法(0)

如何在Python列表中查找项的最后一次出现

说我有这个清单:

li = ["a", "b", "a", "c", "x", "d", "a", "6"]
Run Code Online (Sandbox Code Playgroud)

至于帮助告诉我,没有内置函数返回最后一次出现的字符串(如反之index).基本上,我怎样才能找到"a"给定列表中的最后一次出现?

python list last-occurrence

64
推荐指数
7
解决办法
6万
查看次数

Equivelant to rindex for Python中的列表

有没有一种有效的方法来查找列表中的最后一个匹配项?使用字符串时,您可以使用rindex找到最后一项:

    >>> a="GEORGE"
    >>> a.rindex("G")
    4
Run Code Online (Sandbox Code Playgroud)

...但是这个方法对于列表不存在:

    >>> a=[ "hello", "hello", "Hi." ]
    >>> a.rindex("hello")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'list' object has no attribute 'rindex'
Run Code Online (Sandbox Code Playgroud)

有没有办法在不必构建大循环的情况下获得这个?如果可以避免的话,我宁愿不使用反向方法,因为顺序很重要,我还需要做一些额外的数学运算来找出对象/将来的位置.这似乎很浪费.

编辑:

为了澄清,我需要这个项目的索引号.

python list

8
推荐指数
2
解决办法
8582
查看次数

查找列表python中项的最后一次出现

我希望在序列's'中找到项'x'的最后一次出现,或者如果没有,则返回None,并且第一项的位置等于0

这就是我目前拥有的:

def PositionLast (x,s):

    count = len(s)+1
    for i in s:
        count -= 1
        if i == x:
           return count
    for i in s:
        if i != x:
           return None
Run Code Online (Sandbox Code Playgroud)

当我尝试:

>>>PositionLast (5, [2,5,2,3,5])
>>> 4
Run Code Online (Sandbox Code Playgroud)

这是正确的答案.但是,当我将'x'更改为2而不是5时,我得到:

>>>PositionLast(2, [2,5,2,3,5])
>>> 5
Run Code Online (Sandbox Code Playgroud)

答案应该是2.我很困惑这是如何发生的,如果有人能解释我需要纠正的事情,我将不胜感激.我还想用最基本的代码完成这个.

谢谢.

python position list last-occurrence

6
推荐指数
2
解决办法
5732
查看次数

如何在Python中将多个项目从一个列表移动到另一个列表

我想将一个以上的项目从一个列表移动到另一个列表.

list1 = ['2D','  ','  ','  ','  ','  ','  ','  ','  ']
list2 = ['XX','XX','5D','4S','3D','  ','  ','  ','  ']
list3 = ['XX','XX','XX','8C','7H','6C','  ','  ','  ']
Run Code Online (Sandbox Code Playgroud)

在上面的代码中' '是一个双重空间

我想能够移动'5D','4S','3D'list2'8C','7H','6C'list3.

我已经尝试了下面的代码,但它不起作用.

list1 = ['2D','  ','  ','  ','  ','  ','  ','  ','  ']
list2 = ['XX','XX','5D','4S','3D','  ','  ','  ','  ']
list3 = ['XX','XX','XX','8C','7H','6C','  ','  ','  ']


items_to_be_moved = list2[list2.index('XX')+2 : list2.index('  ')]

list3[list3.index('  ')] = items_to_be_moved
del list2[list2.index('XX')+2 : list2.index('  ')]

print('list2',list2)
print('list3',list3) …
Run Code Online (Sandbox Code Playgroud)

python indexing list

1
推荐指数
1
解决办法
4074
查看次数

标签 统计

list ×4

python ×4

last-occurrence ×2

indexing ×1

position ×1