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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20968823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:40:14  来源:igfitidea点击:

How to iterate over each string in a list of strings and operate on it's elements

pythonstringlist

提问by user3168141

Im new to python and i need some help with this.

我是 python 新手,我需要一些帮助。

TASK : given a list --> words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']

任务:给定一个列表 --> 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.

我需要比较列表中每个字符串的第一个和最后一个元素,如果字符串中的第一个和最后一个元素相同,则增加计数。

Given list is :

给定的清单是:

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

If i try 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.

但是,当我尝试使用 FOR 循环遍历列表中所有字符串的所有元素时。

i get an error.

我得到一个错误。

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

please let me know, how would i achieve comparing the first and the last element of a no. strings in the list.

请让我知道,我将如何比较 no 的第一个和最后一个元素。列表中的字符串。

Thanks in advance.

提前致谢。

采纳答案by Steinar Lima

Try:

尝试:

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

for word in wordsreturns the items of words, not the index. If you need the index sometime, try using enumerate:

for word in words返回 的项目words,而不是索引。如果您有时需要索引,请尝试使用enumerate

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

would output

会输出

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

The -1in word[-1]above is Python's way of saying "the last element". word[-2]would give you the second last element, and so on.

上面的-1inword[-1]是 Python 说“最后一个元素”的方式。word[-2]会给你倒数第二个元素,依此类推。

You can also use a generator to achieve this.

您也可以使用生成器来实现这一点。

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

回答by Johanna

Use range() instead, like the following :

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

for i in range(len(words)):
    ...

回答by ShinTakezou

The reason is that in your second example iis the word itself, not the index of the word. So

原因是在您的第二个示例中i是单词本身,而不是单词的索引。所以

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

would the equivalent of your code.

将相当于您的代码。

回答by fra

The suggestion that using range(len())is the equivalent of using enumerate()is incorrect. They return the same results, but they are notthe same.

使用range(len())等同于使用的建议enumerate()是不正确的。它们返回相同的结果,但它们并不相同。

Using enumerate()actually gives you key/value pairs. Using range(len())does not.

使用enumerate()实际上为您提供了键/值对。使用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 intoa 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 isa 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.

所以我们打印相同的结果,但来源完全不同——处理方式也完全不同。

回答by ibsa

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

回答by Srinivasulu Challa

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)