例如将[‘cat’,‘dog’,‘rabbit’]解析成字符列表
方法一:迭代
wordlist = ['cat','dog','rabbit']
letterlist = [ ]
for aword in wordlist:
for aletter in aword:
letterlist.append(aletter)
print(letterlist)
方法二:列表解析(本质也是一种迭代)
wordlist=['cat','dog','rabbit']
letterlist=[aletter for word in wordlist for aletter in word]
print(letterlist)
最后输出都是:
['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']