Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.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 如何使用列表理解替换字符串中的字符?_Python_List Comprehension - Fatal编程技术网

Python 如何使用列表理解替换字符串中的字符?

Python 如何使用列表理解替换字符串中的字符?,python,list-comprehension,Python,List Comprehension,假设我有一个字符串列表,比如'12hell0',我想把它拆下来说'hello'。 我的想法是: words = ['12hell0','123word', ...] for word in words: stripped = ''.join([i for i in word if not i.isdigit()] 我知道这将创建“地狱”,是否有一种方法可以使用检查它是否为“0”,然后替换为“o”?不确定如何使用多种条件构建理解,但使用常规语句,它将类似于: for word in wor

假设我有一个字符串列表,比如
'12hell0'
,我想把它拆下来说
'hello'
。 我的想法是:

words = ['12hell0','123word', ...]
for word in words:
   stripped = ''.join([i for i in word if not i.isdigit()]
我知道这将创建“地狱”,是否有一种方法可以使用检查它是否为“0”,然后替换为“o”?不确定如何使用多种条件构建理解,但使用常规语句,它将类似于:

for word in words:
    stripped = ''
    word.replace('0','o')
    for char in word:
        if not char.isdigit():
           stripped+=char

感谢您的帮助和指导

我认为您的思路是正确的,仅使用列表理解可能会变得不可读,在这种情况下,将替换逻辑拆分为函数可能是最清晰的解决方案。这样,您就可以应用更多的逻辑或在以后改变主意,而不必干扰太多的代码

def replaceDigits(word):
    stripped = ""
    for char in word:
        if char == "0":
            stripped += "o"
        elif not char.isdigit():
            stripped += char
    return stripped


words = ['12hell0', '123word']
stripped = [replaceDigits(n) for n in words]
print(stripped)

您可以编写一些transform()函数,将所有子字符串替换为要为曲面结构生成的字符串,仅当布尔值为True时才将其应用于i:

stripped = ''.join([transform(i) for i in word if not i.isdigit()]
嵌套条件在列表中是不可能的,
因此,如果需要,可以使用循环。

这是通过列表理解来实现的一种方法,尽管我建议不要使用循环,因为它最终不太可读

我们迭代单词列表,对于每个单词,如果我们找到一个
'0'
,则取字符
'o'
,如果我们找到任何其他数字,则取一个空字符
'
,对于所有其他情况,取字符本身,并通过
str连接所有字符

words = ['12hell0','123word']
words = [''.join('o' if c == '0' else '' if c.isdigit() else c for c in word) for word in words]
print(words)
输出将是

['hello', 'word']

对于
i==“0”
,您可以在列表中添加其他if-else:

words =['12hell0','123word']
new_words = []
for word in words:
  stripped = ''.join([i if not i.isdigit() else 'o' if i == '0' else '' for i in word])
  new_words.append(stripped)
print(new_words)
输出:

['hello', 'word']

如果您真的想让代码看起来不太容易理解(双关语),您可以在一行代码中完成:

我们可以将其分解为:
'o'如果i='0',否则i
-将用
'o'替换
'0'


附加条件
…或i=='0'
将使其成为零,尽管是数字。

您可以这样做:

words = ['12hell0','123word', ...]
new_words = [] # This will receive the changed words

for word in words: # Iterating through array elements
    # This will store the new word.
    new_word = ''.join([ch.replace('0', 'o') for ch in word if not ch.isdigit() or ch == '0'])
    new_words.append(new_word)
print(new_words)
注意:这可能不太像蟒蛇。我建议使用分离的方法,而不是这种方式。代码必须清晰易读,因此其他开发人员很难进行维护


列表理解非常棒,但要小心。

以下是函数式编程方法:

f = lambda arg: list(
    map(
         lambda i: "".join(filter(
             lambda j: j.isalpha(), i.replace("0", "o"))
         ), arg
    )
)

words = ['12hell0','123word']
print(f(words))
# ['hello', 'word']

您可以使用python中的正则表达式库。模式“[^\d]+”搜索一组连续的非数字字符

  • ^:非
  • \d:数字
  • []:单个字符
  • +:一次或多次出现
代码:

输出:['hello','word']

试试这个

>>words=['12hell0','123word']
>>>[“”.join(word中的字符对应字符。如果不是字符,则替换('0','o')。word中的字符对应字符isdigit()
['hello','word']

预期的输出是什么?是
['hello','word']
?@DeveshKumarSingh是的。@DeveshKumarSingh谢谢你的回答,但是所选答案的格式解决了我试图自己解决的问题。这对我来说很有意义。谢谢
f = lambda arg: list(
    map(
         lambda i: "".join(filter(
             lambda j: j.isalpha(), i.replace("0", "o"))
         ), arg
    )
)

words = ['12hell0','123word']
print(f(words))
# ['hello', 'word']
import re
words = ['12hell0','123word']
new_words = [word.replace('0','o') for word in words]
stripped = [re.search('[^\d]+',word).group() if re.search('[^\d]+',word) else '' for word in new_words]