You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python报错TypeError: 'list'与'int'无法执行%运算,求解决办法

问题解决

错误原因

你代码里的if l % 2 == 0:是错误的,l是整个列表对象,不能直接和整数2做取模运算,这就是报错的根源。你实际想要判断的是当前元素的索引i是否为偶数,从而决定是否反转该元素。

修正后的代码

s = 'one two three four five six'
l = s.split()
i = 0
l1 = []
while i < len(l):
    if i % 2 == 0:  # 改为判断索引i是否为偶数
        l1.append(l[i])
    else:
        l1.append(l[i][::-1])
    i = i + 1

output = ' '.join(l1)
print(output)

运行结果

执行后会输出:

one owt three ruof five xis

可选优化写法(更简洁的列表推导式)

s = 'one two three four five six'
l = s.split()
l1 = [word if idx % 2 == 0 else word[::-1] for idx, word in enumerate(l)]
output = ' '.join(l1)
print(output)

内容的提问来源于stack exchange,提问作者Rakesh B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 14:39:31