繁体   English   中英

Python 打印列表中每个字符串的第 n 个字符?

[英]Python print the nth character of every string in a list?

我创建了一些代码,现在只是将字符串添加到列表中,直到用户决定退出,然后它返回该列表的第一个值。

wordList = [] 

while 1:
    user_input = input("Enter a word (or type QUIT to quit): ")
    if user_input=="QUIT":
        break
    wordList.append(user_input)
    
    for i in wordList:
        newList = wordList[0]
    
print ("list of characters: " + str(newList))
print()

但是,我需要的是能够打印每个单词的第 n 个字符。 因此,例如,如果 n 为 5,您将返回以下内容

Enter a word (or type Q to quit): A
Enter a word (or type Q to quit): ABCDE
Enter a word (or type Q to quit): wollongong
Enter a word (or type Q to quit): 123456
Enter a word (or type Q to quit): frog
Enter a word (or type Q to quit): Q
List of characters:
['E', 'o', '5']
wordList = [] 

while 1:
    user_input = input("Enter a word (or type QUIT to quit): ")
    if user_input=="QUIT":
        break
    if len(user_input) > 4:
        wordList.append(user_input[4])
    
print ("list of characters: " + str(wordList))
print()
Enter a word (or type QUIT to quit): A
Enter a word (or type QUIT to quit): ABCDE
Enter a word (or type QUIT to quit): wollonglong
Enter a word (or type QUIT to quit): 123456
Enter a word (or type QUIT to quit): frog
Enter a word (or type QUIT to quit): QUIT
list of characters: ['E', 'o', '5']

你快到了,但看起来你对 [] 符号有点困惑。 如果您有一个变量后跟方括号,它将选择 position。 因此,例如,让我们看一下名为 wordList 的列表。

print(wordList[0])

output 将是“A”。

print(wordList[1])

输出将是“ABCDE”

这同样适用于字符串(这里给你的单词/数字)。 因此,如果您只想打印字符串的第 5 个字母,您可以使用 myString[4] (有点混乱,但 [4] 是第 5 个字母,计为 0)。 如果我们查看您的循环,请使用此逻辑。

for i in wordList:
    newList = wordList[0]

这没有太大意义,您只是一遍又一遍地设置一个名为 newList 的变量等于 wordList 的第一个输入。 如果我要解决这个问题,我会使用循环首先找出单词是否大于 5 个字符,是否将它们添加到新列表中。 然后使用另一个循环打印出我们刚刚创建的新列表的每个输入的第 n 个字符。 有一点 go 如果这更有意义,让我知道您是否需要更多帮助。

你可以把它写成一个简单的循环:

newList = []
n = 5
for w in wordList:
    if len(w) >= n:
        newList.append(w[n-1])

或作为列表理解:

newList = [w[n-1] for w in wordList if len(w) >= n]

在这两种情况下,您的示例数据的 output 是:

['E', 'o', '5']

您需要修改代码以保存列表的第 n 个元素而不是第一个:

wordList = [] 
n = 5
while 1:
    user_input = input("Enter a word (or type QUIT to quit): ")
    if user_input=="QUIT":
        break
    wordList.append(user_input)
    
    for i in wordList:
        if len(newList) > n:  # check if your list has more than n elements
            newList = wordList[n]  # store the nth element
    
print ("list of characters: " + str(newList))
print()
result = []
for word in wordList:
    if len(word) >= 5:
       result.append(word[4])

并且 result[] 将具有 wordList 中每个单词的第 5 个字符(在这里您指定 5)。

所以通常如果我们需要第 n 个字符

result = []
for word in wordList:
    if len(word) >= n:
        result.append(word[n - 1])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM