首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中使用is位数()将数字递增1

在python中使用is位数()将数字递增1
EN

Stack Overflow用户
提问于 2015-11-18 22:01:39
回答 3查看 506关注 0票数 0

我理解,通过使用下面的语法,我可以删除所有出现在我的句子中的数字。我如何修改这个以增加数字,或者实际上对它做任何操作.

代码语言:javascript
复制
no_integers = [x for x in list_add_one_city if not (x.isdigit() or x[0] == '-' and x[1:].isdigit())]

例如..。在你的饮食中,你想吃沙拉作为第一餐,水果作为第二餐,比萨饼作为第三餐。

需要翻译成(使用ISDIGIT()):在你的饮食中,你想把沙拉作为第二餐,水果作为第三餐,披萨作为第四餐。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-11-18 22:15:29

我将使用regex.sub()方法和一个兰卜达函数。

regex可以很容易地检测到数字,然后可以用递增的值替换它们。

代码语言:javascript
复制
import re
s = "You would like to eat salad as meal 1 and fruits as meal 2 and pizza as meal 3 in your diet."

s = re.sub(r'(\d+)', lambda match: str(int(match.group()) + 1), s)
print(s)
# You would like to eat salad as meal 2 and fruits as meal 3 and pizza as meal 4 in your diet.

如果确实需要使用.isdigt(),首先应该使用.split()语句,然后迭代单词列表,如果元素是实际的int,则递增值。最后,不要忘记.join()的结果,以获得您的字符串回来。有人这样想:

代码语言:javascript
复制
words = [str(int(w) + 1) if w.isdigit() else w for w in s.split()]
s = " ".join(words)
票数 3
EN

Stack Overflow用户

发布于 2015-11-18 22:30:27

德尔根的回答很棒,语言也很完美。我只是想补充一下,因为我注意到你正在使用列表理解犯一些错误,我相信这可能是你问题的根源。

清单理解是一个很好的特点。但有几个部分你应该意识到。请参阅下面的图片,查看列表理解的各个部分。

因此,当您使用另一个集合创建列表时。在结尾部分,您使用if语句进行筛选,但实际上您希望前面列表中的所有内容(前一句中的所有单词)都在新列表中。你只想增加那个句子中的所有数字。

这意味着您应该对某些元素执行一个函数。我在您的问题中看到,list comprehension中对list中某些元素(特别是正整数或负整数)执行函数的部分是您想要的。这应该在列表结果字段中完成。下面是我的示例代码:

代码语言:javascript
复制
# Function acting on all elements, increase integer values otherwise return original string
def increment_if_digit(word):
    if x.isdigit():
        value = int(x)
        value += 1
        return str(value)
    elif x[0] is '-' and x[1:].isdigit():
        value = int(x)
        value += 1
        return str(value)
    else:
        return word

# Example usage
sentence = "You would like to eat salad as meal 1 and fruits as meal 2 and pizza as meal 3 in your diet."
no_integers = [increment_if_digit(x) for x in sentence.split()]
print " ".join(no_integers)

其中产出:

代码语言:javascript
复制
You would like to eat salad as meal 2 and fruits as meal 3 and pizza as meal 4 in your diet. 
票数 2
EN

Stack Overflow用户

发布于 2015-11-18 23:21:02

使用tryexcept可以更容易地捕获错误,而不是构建一个小型解析器。

代码语言:javascript
复制
>>> stmt='You would like to eat salad as meal 1 and fruits as meal 2 and pizza as meal 3 in your diet'

def incs(word, n):
    try:
        return str(int(word)+n)
    except ValueError:
        return word

>>> ' '.join([incs(w, 1) for w in stmt.split()])       
You would like to eat salad as meal 2 and fruits as meal 3 and pizza as meal 4 in your diet     
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33791279

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档