我在从'RND'之后的列表中获取数字时遇到问题:

myList = [['1123-TDT','10593917/5422','RND','20 .5','QWTQWGSAG','RND','40'],
          ['1156-TDT','51205915/6166','ASDWT','111551','RND','35']]


如果列表项(myList [1])中只有一个RND,我可以在RND之后得到数字。但是,如果有两个'em(myList [0]),则什么也不会发生。

我所拥有的例子:

myList = [['1123-TDT','10593917/5422','RND','20 .5','QWTQWGSAG','RND','40'],
          ['1156-TDT','51205915/6166','ASDWT','111551','RND','35']]

listLen = len(myList)

对于范围内的x(listLen):
    如果myList [x]中为“ RND”:
        y = myList [x] .index('RND')
        z = myList [x] [y + 1]
        打印(z)


输出看起来像这样:

20.5
35


但我希望是:

20.5 40
35


提前致谢!

最佳答案

您需要访问每个子列表和子列表中的每个子元素,然后在当前元素等于"RND"的情况下在当前索引之后获得该元素:

print( [sub[ind] for sub in myList for ind, ele in enumerate(sub,1) if ele == "RND"])
['20.5', '40', '35']


使用两个普通循环:

# iterate over each sublist
for sub in myList:
    # check every element in each sublist for "RND"
    # if we find a match print the next element in the list
    for ind, ele in enumerate(sub,1):
        if ele == "RND":
            print(sub[ind])


我们使用enumerate(sub,1),其中1是起始索引,因此如果使用sub[ind]的起始索引,则在访问0时将得到下一个元素而不是当前元素。

y = myList[x].index('RND')仅使您第一次出现。

如果要将每个子列表的输出打印在一行上,请使用end=" "

for sub in myList:
    # check every element in each sublist for "RND"
    # if we find a match print the next element in the list
    for ind, ele in enumerate(sub,1):
        if ele == "RND":
            print(sub[ind],end=" ")
    print()
20.5 40
35

关于python - 在特定字符串后获得多个数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28461926/

10-12 02:00