如何在字符串中提取中字母?

发布于 2025-02-08 05:49:41 字数 562 浏览 0 评论 0原文

我如何使用列表理解来提取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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

禾厶谷欠 2025-02-15 05:49:41

使用以下代码,

L = [x[int(len(x) / 2)] for x in Q[1] if len(x) % 2]
print(L)

您将获得['a','n','e']


if len(x) % 2

只有在len(x)%2的结果不同时才是正确的比零,例如,字符串具有奇数字符时。

x[int(len(x) / 2)]

列表理解中的这部分将通过计算列表的长度并在中途进行索引来获取中间字母。

Using the following code

L = [x[int(len(x) / 2)] for x in Q[1] if len(x) % 2]
print(L)

you will get ['a', 'n', 'e']


if len(x) % 2

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.

x[int(len(x) / 2)]

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文