简体   繁体   English

如何遍历字符串列表中的每个字符串并对其元素进行操作?

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

Given a list:给定一个列表:

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

I need to compare the first and the last element of each string in the list.我需要比较列表中每个字符串的第一个和最后一个元素。 If the first and the last element in the string is the same, then increment the count.如果字符串中的第一个和最后一个元素相同,则增加计数。

If I try it manually, I can iterate over each element of the strings in the list:如果我手动尝试,我可以遍历列表中字符串的每个元素:

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

But, when I try to iterate over all the elements of all the strings in the list, using a for loop, I get an error.但是,当我尝试使用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

ERROR:错误:

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

How would I achieve comparing the first and the last element of a list of strings?如何比较字符串列表的第一个和最后一个元素?

Try:尝试:

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

for word in words returns the items of words , not the index. for word in words返回的项目words ,而不是指数。 If you need the index sometime, try using enumerate :如果您有时需要索引,请尝试使用enumerate

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

would output会输出

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

The -1 in word[-1] above is Python's way of saying "the last element".-1word[-1]以上是说“最后一个元素”的Python的方式。 word[-2] would give you the second last element, and so on. word[-2]会给你倒数第二个元素,依此类推。

You can also use a generator to achieve this.您也可以使用生成器来实现这一点。

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

The reason is that in your second example i is the word itself, not the index of the word.原因是在您的第二个示例中, i是单词本身,而不是单词的索引。 So所以

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

would the equivalent of your code.将相当于您的代码。

The suggestion that using range(len()) is the equivalent of using enumerate() is incorrect.使用range(len())等同于使用enumerate()是不正确的。 They return the same results, but they are not the same.它们返回相同的结果,但它们并不相同。

Using enumerate() actually gives you key/value pairs.使用enumerate()实际上为您提供了键/值对。 Using range(len()) does not.使用range(len())不会。

Let's check range(len()) first (working from the example from the original poster):让我们首先检查range(len()) (从原始海报的示例中工作):

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

This gives us a simple list:这给了我们一个简单的列表:

[0, 1, 2, 3, 4]

... and the elements in this list serve as the "indexes" in our results. ...并且此列表中的元素用作我们结果中的“索引”。

So let's do the same thing with our enumerate() version:所以让我们对enumerate()版本做同样的事情:

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

This certainly doesn't give us a list:这当然不会给我们一个列表:

<enumerate object at 0x7f6be7f32c30>

...so let's turn it into a list, and see what happens: ...所以让我们把它变成一个列表,看看会发生什么:

print list(enumerate(words))

It gives us:它给了我们:

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

These are actual key/value pairs.这些是实际的键/值对。

So this ...所以这...

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

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

... actually takes the first list (Words), and creates a second , simple list of the range indicated by the length of the first list. ... 实际上采用第一个列表 (Words),并创建第二个简单列表,其范围由第一个列表的长度指示。

So we have two simple lists, and we are merely printing one element from each list in order to get our so-called "key/value" pairs.所以我们有两个简单的列表,我们只是从每个列表中打印一个元素以获得我们所谓的“键/值”对。

But they aren't really key/value pairs;但它们并不是真正的键/值对; they are merely two single elements printed at the same time, from different lists.它们只是从不同列表中同时打印的两个单个元素。

Whereas the enumerate () code:enumerate ()代码:

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

... also creates a second list. ... 还创建了第二个列表。 But that list actually is a list of key/value pairs, and we are asking for each key and value from a single source -- rather than from two lists (like we did above).但该列表实际上一个键/值对列表,我们要求来自单个来源的每个键和值——而不是来自两个列表(就像我们上面所做的那样)。

So we print the same results, but the sources are completely different -- and handled completely differently.所以我们打印相同的结果,但来源完全不同——处理方式也完全不同。

The following code outputs the number of words whose first and last letters are equal.以下代码输出第一个和最后一个字母相等的单词数。 Tested and verified using a python online compiler :使用python 在线编译器进行测试和验证:

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

Output:输出:

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

You are iterating trough items in words but you have to iterate through item's length:您正在遍历单词中的项目,但您必须遍历项目的长度:

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)

In your case i[0] is 'aba' because i is calculated from items in words:在您的情况下, i[0] 是 'aba' 因为 i 是根据单词中的项目计算的:

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

the output is:输出是:

aba阿坝

You can solve this problem using sum() and a generator expression.您可以使用sum()和生成器表达式来解决此问题。 When intepreted as integers, booleans that are True have a value of 1 , and booleans that are False have a value of 0 .当被解释为整数时,为True的布尔值的值为1 ,为False的布尔值的值为0 So, we can do the following:因此,我们可以执行以下操作:

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

Use range() instead, like the following :使用 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