2016-12-22 26 views
2

我有一个字符串说 string = 'bcde'改变蟒蛇单词的第一个字母在字母表中的所有字母,并生成一个列表

我想要做的是从更换的第一个字母string(即b)并将其替换为字母表中每个字母的迭代,直到z。

所需的输出:

['acde', 'bcde', 'ccde', 'dcde', 'ecde', 'fcde', ..., 'zcde'] 

这是我目前使用的代码,但我得到了错误的输出:

a = 'bcde' 
a = list(a) 
alphabet = 'abcdefghijklmnopqrstuvwxyz' 
alphabet = list(alphabet) 
final = [] 
for n,i in enumerate(a): 
    if i==b: 
     a[i] = [alphabet[x] for x in alphabet ] 
     final.append(a[i]) 
+0

你不想遍历'a',因为你只想改变'a'的第一个字母。你也可以遍历字母表,最简单的方法是将字母连接到'a [1:]'。 – roganjosh

+0

喜欢它或讨厌它在这里它是在一个地图'lambda x:x [0] + x [1],zip(alphabet,itertools.cycle((s [1:],))))' – themistoklik

+0

@ themistoklik'itertools.repeat(s [1:])'比'itertools.cycle((s [1:],))'更简洁。而在Python 3中,您需要将'map'调用包装在'list()'中。 –

回答

4

它可以用列表理解真的很容易做到

a = 'bcde' 
alphabet = 'abcdefghijklmnopqrstuvwxyz' 
post_string = a[1:] 
final = [letter+post_string for letter in alphabet] 
+1

你不需要把'字母'变成一个列表。你可以迭代字符串。你可以做'import string'然后它是'... for string.ascii_lowercase]' –

+0

你是对的,但我不认为他真的希望字母表真的是字母表,它可能是另一种元素在列表中。 – iFlo

+0

或简单地说'[x + a [1:] for map in map(chr,range(97,123))]' –

1

这是所有你需要:

alphabet = 'abcdefghijklmnopqrstuvwxyz' 

a='bcde' 
new_list = [] 
for i in alphabet: 
    new_list.append(i+a[1:]) 
+1

那么什么是需要创建一个列表?.. for循环使用 – sachsure

+0

Whaaat?他指定了期望的输出。 – iFlo

+1

因为这是OP的意图。而'print'与创建列表有着根本的不同。一个是数据结构。 – roganjosh

0

尝试以下操作:

s = 'bcde' 
final = [] 
if s[0] == 'b': 
    final = ['{}{}'.format(i, s[1:]) for i in 'abcdefghijklmnopqrstuvwxyz'] 
print(final) 

输出:

>>> final 
['acde', 'bcde', 'ccde', 'dcde', 'ecde', 'fcde', 'gcde', 'hcde', 'icde', 'jcde', 'kcde', 'lcde', 'mcde', 'ncde', 'ocde', 'pcde', 'qcde', 'rcde', 'scde', 'tcde', 'ucde', 'vcde', 'wcde', 'xcde', 'ycde', 'zcde'] 
1

因为人们总是可以mispell字母:

s = 'bcde' 
final = list(map(lambda x: chr(x + ord('a')) + s[1:], range(26))) 
2

这里所有的解决方案都太复杂/在顶部,只需使用简单的列表理解:

text = 'abcd' 
final = [c + text[1:] for c in 'abcdefghijklmnopqrstvuwxyz'] 

如果你需要用拼音多次使用import string然后string.ascii_lowercase

相关问题