Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.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 (for)和(if)条件的单行代码错误_Python - Fatal编程技术网

Python (for)和(if)条件的单行代码错误

Python (for)和(if)条件的单行代码错误,python,Python,将一个句子中的所有单词从存储在变量c中的特定字母开始反转的程序 我想知道单线和多线条件的区别 当我这样写的时候,它是有效的 l = "word searches are super fun" c = 's' for i in l.split(): if i[0] == c: l = l.replace(i, i[::-1]) print(l) 这是错误的 l="word searches are super fun" c='s' l=l.replace

将一个句子中的所有单词从存储在变量c中的特定字母开始反转的程序 我想知道单线和多线条件的区别

当我这样写的时候,它是有效的

l = "word searches are super fun"
c = 's' 
for i in l.split():
        if i[0] == c:
            l = l.replace(i, i[::-1])
print(l)
这是错误的

l="word searches are super fun"
c='s'
l=l.replace(i, i[::-1]) for i in l.split() if i[0]==c
print(l) 
输出应该是 (单词sehcraes是repus fun) 但事实确实如此
(无效语法)

不能在所有情况下为/if使用
。您可以在
列表理解
(或类似内容)中使用它


您不能在所有情况下使用
for/if
——只能在
列表理解
和类似情况下使用。
l = "word searches are super fun"
c = 's'

# create list with new words - using list comprehension
l = [ i[::-1] if i[0]==c else i for i in l.split() ]

# concatenate list into one string
l = ' '.join(l)

print(l)