如何访问lis列表中的每个字符串

2024-04-19 03:20:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是输入多行,每行由多个语言。语言任务是将长度为奇数的单词大写,将长度为奇数的单词小写 长度均匀。 我的代码现在是这样的,你能帮我解决它吗?你知道吗

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])

it should look like this


Tags: 代码in语言trueforinputlenif
3条回答

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

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)

ij不是索引,它们是子列表和单词他们自己。你呢我们可以做:

for i in first:  # i is a list of strings
    for j in range(len(i)):  # you do need the index to mutate the list
        if len(i[j]) % 2 == 0:
            i[j] = i[j].lower()
        else:
            i[j] = i[j].upper()
        print(' '.join(i))

你忘了把线重新连接起来。此外,从软件设计的角度来看,您在代码片段中做了很多工作:最好将功能封装在函数中,例如:

def wordcase(word):
    if len(word) % 2 == 0:  # even
        return word.lower()
    else:                   # odd
        return word.upper()

然后我们甚至可以“在线”执行处理(如每行一行):

while True:
    line = input()
    if not line:
        break
    else:
        print(' '.join(wordcase(word) for word in line.split()))

相关问题 更多 >