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

时间:2018-09-27 14:57:33

标签: python list

我有一项任务是输入多行,每行由多个单词组成,任务是将具有奇数长度的单词大写,并以 长度均匀。  我的代码现在看起来像这样,您能帮我解决吗?

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

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

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

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)

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

我认为您不需要使用ij。您可以只遍历字符串中的单词。

此外,尽管它可能不会加快速度,但您不需要elif,而只需使用else。只有两个选项,奇数和偶数,因此您只需要检查一次即可。

sentance = 'I am using this as a test string with many words'

wordlist = sentance.split()
fixed_wordlist = []

for word in wordlist:
    if len(word)%2==0:
        fixed_wordlist.append(word.lower())
    else:
        fixed_wordlist.append(word.upper())

print(sentance, '\n', wordlist, '\n', fixed_wordlist)