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

Python列表拼接报错求助:如何按索引奇偶拆分字符列表?

Fixing Your Python String Splitting Issue

Hey there! Let's break down why you're seeing that can only concatenate list (not 'int') to list error and fix your code to meet your requirements.

First, the root causes of the error:

  • You're trying to add an integer (i, the index) directly to a list (even_letters/odd_letters). Python doesn't allow concatenating lists with integers—you need to add actual characters from your string to the lists instead.
  • Your way of checking even/odd indices is incorrect. Using i/2 == 0 won't work for even indices like 2 or 4 (since 2/2 = 1, which isn't 0). Instead, use the modulo operator % to reliably check if an index is even or odd.

Here's the corrected code:

word = input("Type: ")
word_list = list(word)  # Renamed for clarity, original variable name works too
print(word_list)

odd_letters = []
even_letters = []
length = len(word_list)  # No need to convert to int—len() already returns an integer

for i in range(length):
    if i % 2 == 0:
        # Index 0, 2, 4... go to odd_letters as per your requirement
        odd_letters.append(word_list[i])
    else:
        # Index 1, 3, 5... go to even_letters
        even_letters.append(word_list[i])

print(odd_letters)
print(even_letters)

Key changes made:

  • Used i % 2 == 0 to correctly identify even indices (0, 2, 4...) which you want stored in odd_letters.
  • Replaced even_letters + i with append(word_list[i])—this adds the actual character from the string to the list, which is what you need. The append() method is also more efficient than list concatenation for this use case.
  • Removed the unnecessary int() conversion on len(word)—len() already returns an integer, so converting it is redundant.

Bonus: A more concise version using list comprehensions

If you want to simplify your code once you're comfortable with the basics, you can use list comprehensions to split the characters in one line each:

word = input("Type: ")
odd_letters = [word[i] for i in range(0, len(word), 2)]
even_letters = [word[i] for i in range(1, len(word), 2)]

print(odd_letters)
print(even_letters)

This uses range(start, stop, step) to directly iterate over the even/odd indices without needing an explicit if/else check.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:40:52