Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字符串末尾拆分字符串中的3个空格分隔值?_Python_String - Fatal编程技术网

Python 从字符串末尾拆分字符串中的3个空格分隔值?

Python 从字符串末尾拆分字符串中的3个空格分隔值?,python,string,Python,String,我有这个字符串: "peter bull team tunnel rat 10 20 30" 我想做的是从末尾提取最后3个值: 30 20 10 如何以最智能的方式将最后3个字段向后剥离 一个简单的方法是使用rsplit: s = "peter bull team tunnel rat 10 20 30" n = 3 out = s.rsplit(maxsplit=n)[-n:] # ['10', '20', '30'] 如果需要整数列表: list(map(int, out)

我有这个字符串:

"peter bull team tunnel rat 10 20 30"
我想做的是从末尾提取最后3个值:

 30
 20
 10 

如何以最智能的方式将最后3个字段向后剥离

一个简单的方法是使用
rsplit

s = "peter bull team tunnel rat 10 20 30"

n = 3
out = s.rsplit(maxsplit=n)[-n:]
# ['10', '20', '30']

如果需要整数列表:

list(map(int, out))
# [10, 20, 30]

在注释之后,如果要将文本追加到最后几位之前,一种方法是:

s, *d = s.rsplit(sep=' ',maxsplit=3)
' '.join([*d, s])
# '10 20 30 peter bull team tunnel rat'

可以使用split和reversed()函数向后获取值:

data = "peter bull team tunnel rat 10 20 30"

print (list(reversed(data.split()[-3:])))
输出:

['30','20','10']

使用
split()
和列表理解

  • list.reverse()
    -方法反转给定列表的元素
Ex.

sentence = "peter bull team tunnel rat 10 20 30"
num = [int(s) for s in sentence.split() if s.isdigit()]
num.reverse()
print(num)
O/p:

[30, 20, 10]

sort在本例中使用不正确,如果他有字符串,例如“peter bull team tunnel rat 50 20 30”@ncica,请在这里评论之前使用您的字符串示例测试我的代码。我测试它!如果你有“peter bull team tunnel rat 50 20 30”,它将返回[50,30,20],但它应该返回[30,20,50]。OP要求“倒转最后3个字段”@ncica你是对的,我没有读任何问题,只是看到了预期的输出,答案更新了。不用担心,这只是一个善意的评论:)@bharatkwhat如果我想以“peter bull team tunnel rat”结束原始字符串-是否有方法可以识别剥离时的最后位置,或者可以智能完成?更新。结果是否为字符串?否则,只需将这两个列表附加到@MdTp