簡體   English   中英

如何遍歷字符串列表中的每個字符串並對其元素進行操作?

[英]How to iterate over each string in a list of strings and operate on its elements?

給定一個列表:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']

我需要比較列表中每個字符串的第一個和最后一個元素。 如果字符串中的第一個和最后一個元素相同,則增加計數。

如果我手動嘗試,我可以遍歷列表中字符串的每個元素:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
w1 = words[0]
print w1
aba

for i in w1:
   print i
 
a
b
a

if w1[0] == w1[len(w1) - 1]:
   c += 1
   print c
 
1

但是,當我嘗試使用for循環遍歷列表中所有字符串的所有元素時,出現錯誤。

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
c = 0
for i in words:
     w1 = words[i]
     if w1[0] == w1[len(w1) - 1]:
       c += 1
     print c

錯誤:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: list indices must be integers, not str

如何比較字符串列表的第一個和最后一個元素?

嘗試:

for word in words:
    if word[0] == word[-1]:
        c += 1
    print c

for word in words返回的項目words ,而不是指數。 如果您有時需要索引,請嘗試使用enumerate

for idx, word in enumerate(words):
    print idx, word

會輸出

0, 'aba'
1, 'xyz'
etc.

-1word[-1]以上是說“最后一個元素”的Python的方式。 word[-2]會給你倒數第二個元素,依此類推。

您也可以使用生成器來實現這一點。

c = sum(1 for word in words if word[0] == word[-1])

原因是在您的第二個示例中, i是單詞本身,而不是單詞的索引。 所以

for w1 in words:
     if w1[0] == w1[len(w1) - 1]:
       c += 1
     print c

將相當於您的代碼。

使用range(len())等同於使用enumerate()是不正確的。 它們返回相同的結果,但它們並不相同。

使用enumerate()實際上為您提供了鍵/值對。 使用range(len())不會。

讓我們首先檢查range(len()) (從原始海報的示例中工作):

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
    print range(len(words))

這給了我們一個簡單的列表:

[0, 1, 2, 3, 4]

...並且此列表中的元素用作我們結果中的“索引”。

所以讓我們對enumerate()版本做同樣的事情:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']    
   print enumerate(words)

這當然不會給我們一個列表:

<enumerate object at 0x7f6be7f32c30>

...所以讓我們把它變成一個列表,看看會發生什么:

print list(enumerate(words))

它給了我們:

[(0, 'aba'), (1, 'xyz'), (2, 'xgx'), (3, 'dssd'), (4, 'sdjh')]

這些是實際的鍵/值對。

所以這...

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']

for i in range(len(words)):
    print "words[{}] = ".format(i), words[i]

... 實際上采用第一個列表 (Words),並創建第二個簡單列表,其范圍由第一個列表的長度指示。

所以我們有兩個簡單的列表,我們只是從每個列表中打印一個元素以獲得我們所謂的“鍵/值”對。

但它們並不是真正的鍵/值對; 它們只是從不同列表中同時打印的兩個單個元素。

enumerate ()代碼:

for i, word in enumerate(words):
    print "words[{}] = {}".format(i, word)

... 還創建了第二個列表。 但該列表實際上一個鍵/值對列表,我們要求來自單個來源的每個鍵和值——而不是來自兩個列表(就像我們上面所做的那樣)。

所以我們打印相同的結果,但來源完全不同——處理方式也完全不同。

以下代碼輸出第一個和最后一個字母相等的單詞數。 使用python 在線編譯器進行測試和驗證:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']  
count = 0  
for i in words:  
     if i[0]==i[-1]:
        count = count + 1  
print(count)  

輸出:

$python main.py
3
c=0
words = ['challa','reddy','challa']

for idx, word in enumerate(words):
    if idx==0:
        firstword=word
        print(firstword)
    elif idx == len(words)-1:
        lastword=word
        print(lastword)
        if firstword==lastword:
            c=c+1
            print(c)

您正在遍歷單詞中的項目,但您必須遍歷項目的長度:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
c = 0
for i in range(len(words)):
    w1 = words[i]
    if w1[0] == w1[len(w1) - 1]:
      c += 1
    print (c)

在您的情況下, i[0] 是 'aba' 因為 i 是根據單詞中的項目計算的:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
c = 0
for i in words:
print(i)

輸出是:

阿壩

您可以使用sum()和生成器表達式來解決此問題。 當被解釋為整數時,為True的布爾值的值為1 ,為False的布爾值的值為0 因此,我們可以執行以下操作:

sum(word[0] == word[-1] for word in words)

使用 range() 代替,如下所示:

for i in range(len(words)):
    ...
for i,j in enumerate(words): # i---index of word----j
     #now you got index of your words (present in i)
     print(i) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM