如何提取一部分字符串列表? [英] How to extract a part of a list of strings?

查看:133
本文介绍了如何提取一部分字符串列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串列表,我想提取每个字符串的前6个字符并将它们存储在新列表中.

I have a list of strings and I want to extract the first 6 characters of each string and store them in a new list.

我可以遍历列表并提取前6个字符,并将其附加到新列表中.

I can loop through the list and extract the first 6 characters and append them to a new list.

y = []
for i in range(len(x)):
    y.append(int(x[i][0:6]))

我想知道是否有一种优雅的一线解决方案. 我尝试了以下方法:

I want to know if there is an elegant one line solution for that. I tried the following:

y = x[:][0:6]

但是它返回前6个字符串的列表.

But it returns a list of the first 6 strings.

推荐答案

尝试一下:

y = [z[:6] for z in x]

与此相同:

y = []               # make the list
for z in x:          # loop through the list
    y.append(z[:6])  # add the first 6 letters of the string to y

这篇关于如何提取一部分字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆