[英]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.