首页 > 解决方案 > 如何访问列表列表中的每个字符串

问题描述

我的任务是输入多行,每行由多个单词组成。任务是将奇数长度的单词大写,偶数长度的单词小写。我的代码现在看起来像这样,你能帮我解决吗?

first = []
while True:

    line = input().split()
    first.append(line)
    if len(line) < 1:
        break
for i in first:
    for j in i:
        if len(line[i][j]) % 2 == 0:
            line[i][j] = line[i][j].lower()
        elif len(line[i][j]) % 2 != 0:
            line[i][j] = line[i][j].upper()
         print(first[i])

它应该看起来像这样

标签: pythonlist

解决方案


因此,查看图像中的输入输出,这是一个更好的解决方案

sentences = []
while True:
    word_list = input().split()
    sentences = [*sentences, word_list]
    if len(word_list) < 1:
        break

所以现在你已经从命令行输入你可以做

[word.upper() if len(word)%2 == 1 else word.lower() for word_list in sentences for word in word_list]

或者你可以提取到一个函数中

def apply_case(word):
  if len(word)%2:
    return word.upper()
  return word.lower()

new_sentences = [apply_case(word) for word_list in sentences for word in word_list]

现在你可以像这样打印它

output = "\n".join([" ".join(word_list) for word_list in new_sentences])
print(output)

推荐阅读