【问题标题】:how to convert a list of strings into a list of letters in python?如何将字符串列表转换为python中的字母列表?
【发布时间】:2021-11-10 22:07:37
【问题描述】:

我该如何转这个:

list = ['hi', 'my', 'name', 'is']

进入这个:

list = ['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's']

【问题讨论】:

标签: python string list letter


【解决方案1】:

试试:

l = ['hi', 'my', 'name', 'is']
output = list(''.join(l))
print(output)

输出:

['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's']

【讨论】:

    【解决方案2】:

    您可以利用可以像列表一样迭代字符串的事实:

    words = ['hi', 'my', 'name', 'is']
    letters = [letter for word in words for letter in word]
    print(letters)
    

    输出:

    ['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's']
    

    【讨论】:

      【解决方案3】:

      已编辑,来自@juanpa.arrivillaga 的提示

      list = ['hi', 'my', 'name', 'is']
      
      newList = []
      for x in list: 
          for y in x: 
              newList.append(y)
      
      print(newList)
      

      输出:

      ['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's']
      

      【讨论】:

      • ...哎呀。太重了。
      • 我不会对此投反对票,但您不应该在 Python 中迭代 range。相反,直接遍历序列,所以使用for string in mylist: for char in string: new_list.append(char)
      • 谢谢@juanpa.arrivillaga 的小费
      猜你喜欢
      • 1970-01-01
      • 2017-04-10
      • 2019-07-31
      • 2017-11-15
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多