【问题标题】:How to iterate over each string in a list of strings and operate on it's elements如何遍历字符串列表中的每个字符串并对其元素进行操作
【发布时间】:2014-01-24 23:16:45
【问题描述】:

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

TASK : 给定一个列表 --> words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']

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

给定列表是:

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

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

提前致谢。

【问题讨论】:

  • 对列表的迭代返回其元素而不是索引,因此会出现错误。
  • 你的 Python 单线器可以做你想做的事情(但不解决或解释错误)看起来像:c = sum([1 if w[0] == w[-1] else 0 for w in words])。但这对您没有真正的帮助,除非您开始掌握列表理解的窍门(甚至更短:c = sum([int(w[0] == w[-1]) for w in words]))。
  • @Evert 你可以放弃int 电话和[] 以及.. ;-)
  • @AshwiniChaudhary 嗯,我不喜欢这样对布尔值求和,但我想隐式转换在这里有效。我让它站着,否则你的评论将没有意义;-)。

标签: python string list


【解决方案1】:

试试:

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.

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

您也可以使用生成器来实现此目的。

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

【讨论】:

    【解决方案2】:

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

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

    将相当于您的代码。

    【讨论】:

      【解决方案3】:

      使用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]
      

      ...实际上取第一个列表(单词),并创建一个second,由第一个列表的长度指示的范围的简单列表。

      所以我们有两个简单的列表,我们只是从每个列表中打印一个元素以获得我们所谓的“键/值”对。

      但它们并不是真正的键/值对;它们只是同时打印的两个单个元素,来自不同的列表。

      enumerate () 代码:

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

      ... 还会创建第二个列表。但该列表实际上一个键/值对列表,我们要求来自单一来源的每个键和值——而不是来自两个列表(就像我们上面所做的那样)。

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

      【讨论】:

        【解决方案4】:

        以下代码输出首尾字母相等的单词数。使用python online compiler 测试和验证:

        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
        

        【讨论】:

          【解决方案5】:
          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)
          

          【讨论】:

          • 你能解释一下你的代码的更多细节吗?
          • 嗨,Serenity,基本上,如果第一个单词和最后一个单词相同,则代码将获取增量编号。
          【解决方案6】:

          您正在迭代单词中的项目,但您必须迭代项目的长度:

          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)
          
          

          输出是:

          阿巴

          【讨论】:

            【解决方案7】:

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

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

            【讨论】:

              【解决方案8】:
              for i,j in enumerate(words): # i---index of word----j
                   #now you got index of your words (present in i)
                   print(i) 
              

              【讨论】:

              猜你喜欢
              • 2022-01-12
              • 2019-04-01
              • 2011-10-30
              • 2015-12-17
              • 2020-11-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-12-15
              相关资源
              最近更新 更多