切片到“ “Python中的空格

发布于 2024-11-03 18:20:55 字数 155 浏览 2 评论 0 原文

If L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]]

如何对 L 进行切片以使所有内容都达到第一个空格

['abc,'foo','bar']

If L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]]

How would slice L to get everything up to the first space

['abc,'foo','bar']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(5

这样的小城市 2024-11-10 18:20:55
In [1]: L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]]

In [2]: [x[0].split(' ')[0] for x in L]
Out[2]: ['abc', 'foo', 'bar']
In [1]: L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]]

In [2]: [x[0].split(' ')[0] for x in L]
Out[2]: ['abc', 'foo', 'bar']
倦话 2024-11-10 18:20:55
L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]]
print [x[0].split()[0] for x in L]
L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]]
print [x[0].split()[0] for x in L]
小红帽 2024-11-10 18:20:55
for i in range(len(L)):
    s = L[i][0]
    s = s.split(' ')[0]
    L[i] = s
for i in range(len(L)):
    s = L[i][0]
    s = s.split(' ')[0]
    L[i] = s
你的往事 2024-11-10 18:20:55

在您呈现的情况下,空格始终出现在同一位置。如果您知道会出现这种情况,您可以执行以下操作:

L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]]
L2 = [x[0][0:3] for x in L]
print L2

输出:

['abc', 'foo', 'bar']

当然,如果空格可以出现在不同的位置,那么您最好使用 str.split()

In the cases you present, the spaces always occur in the same postion. If you know this will be the case, you could do something like:

L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]]
L2 = [x[0][0:3] for x in L]
print L2

Output:

['abc', 'foo', 'bar']

Of course, if the spaces can occur in different positions, then you'd be better off using one of the solutions using str.split().

不甘平庸 2024-11-10 18:20:55

我发现列表理解有时更难以阅读,我更愿意将循环和提取分开:

def extract(element):
    """Extracts the string until the first space of the first element of a list
    >>> extract(['abc 1234',2])
    'abc'
    """
    return element[0].split()[0]

这样您就可以对单个元素进行一些测试:

extract(L[2])
'bar'

然后将其应用于列表理解或使用映射 [将函数应用于列表的每个元素]:

map(extract,L)
['abc', 'foo', 'bar']

I find that list comprehensions are sometimes more difficult to read, I would prefer to keep separate the looping and the extraction:

def extract(element):
    """Extracts the string until the first space of the first element of a list
    >>> extract(['abc 1234',2])
    'abc'
    """
    return element[0].split()[0]

so that you can do some tests on single elements:

extract(L[2])
'bar'

and then apply this with a list comprehension or using map [applies function to each element of a list]:

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