如何在字符串中提取中字母?
我如何使用列表理解来提取Q [1]中所有字符串的所有中间字母:
Q = [ ["Elizabeth","Victoria","Elizabeth"],
["Eleanor","Blanche","Margaret","Isabella","Anne","Catherine","Marguerite","Mary","Anne"],
["Padmini","Chennamma","Sultana","Holkar"],
["Artemisia","Kratesipolis","Nikaia","Olympias"]
]
到目前为止,我只有以下内容:
L = [ x for x in Q[1] if len(x) % 2 != 0 ]
print(L)
但是,这只会打印出所有带有奇数字符的字符串可以找到。
['Eleanor', 'Blanche', 'Catherine']
输出必须是:
['a','n','e']
How can I use list comprehension to extract all the middle letters of all the strings in Q[1]:
Q = [ ["Elizabeth","Victoria","Elizabeth"],
["Eleanor","Blanche","Margaret","Isabella","Anne","Catherine","Marguerite","Mary","Anne"],
["Padmini","Chennamma","Sultana","Holkar"],
["Artemisia","Kratesipolis","Nikaia","Olympias"]
]
So far all I have is this:
L = [ x for x in Q[1] if len(x) % 2 != 0 ]
print(L)
But this only prints out all the strings with an odd number of characters, in which a middle letter can be found.
['Eleanor', 'Blanche', 'Catherine']
The output has to be:
['a','n','e']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用以下代码,
您将获得
['a','n','e']
只有在
len(x)%2
的结果不同时才是正确的比零,例如,字符串具有奇数字符时。列表理解中的这部分将通过计算列表的长度并在中途进行索引来获取中间字母。
Using the following code
you will get
['a', 'n', 'e']
Will be true only when the result of
len(x) % 2
is different than zero, e.g. when the string has a odd number of characters.This piece of the list comprehension will take the middle letter by calculating the length of the list and taking the index at the half way.