我有一个如下所示的列表:
['48638 0 Q qp32', '48708 0 Q qp32', '48736 0 Q batch', '48737 0 Q batch', '48738 588:30:5 R qp32', '48758 45:00:40 R qp32', '48763 274:19:4 R qp256', '48772 0 Q qp32', '48782 02:25:16 R qp256', '48783 0 Q qp256', '48786 0 Q qp256', '48802 05:57:29 R qp64']
如何根据48638
或Q
等参数提取R
之类的数字,并将输出放入单独的列表中?由于这是在整个列表中,我无法找出任何解决方案。
输出必须在两个单独的列表中:
Q
,则应打印48638, 48708, 48736, 48783, 48786
R
,则应打印48738, 48802, 48782, 48763
答案 0 :(得分:2)
您可以使用in
成员资格测试来查看该字符是否存在,然后使用字符串拆分来提取第一个元素:
parameter = 'R' # or 'Q'
[s.partition(' ')[0] for s in yourlist if parameter in s]
这会产生字符串(所以['48638', '48708', '48736', '48783', '48786'] for
' Q' ). If you needed *integers*, simply add
int()`:
[int(s.partition(' ')[0]) for s in yourlist if parameter in s]
演示:
>>> yourlist = ['48638 0 Q qp32', '48708 0 Q qp32', '48736 0 Q batch', '48737 0 Q batch', '48738 588:30:5 R qp32', '48758 45:00:40 R qp32', '48763 274:19:4 R qp256', '48772 0 Q qp32', '48782 02:25:16 R qp256', '48783 0 Q qp256', '48786 0 Q qp256', '48802 05:57:29 R qp64']
>>> parameter = 'R'
>>> [s.partition(' ')[0] for s in yourlist if parameter in s]
['48738', '48758', '48763', '48782', '48802']
>>> [int(s.partition(' ')[0]) for s in yourlist if parameter in s]
[48738, 48758, 48763, 48782, 48802]
答案 1 :(得分:0)
def get_numbers(your_list, typ):
res = []
for e in your_list:
ls = e.split()
if ls[2] == typ:
res.append(int(ls[0]))
return res
答案 2 :(得分:0)
data=['48638 0 Q qp32', '48708 0 Q qp32', '48736 0 Q batch', '48737 0 Q batch', '48738 588:30:5 R qp32', '48758 45:00:40 R qp32', '48763 274:19:4 R qp256', '48772 0 Q qp32', '48782 02:25:16 R qp256', '48783 0 Q qp256', '48786 0 Q qp256', '48802 05:57:29 R qp64']
qs=[int(s.split(' ')[0]) for s in data if 'Q' in s]
rs=[int(s.split(' ')[0]) for s in data if 'R' in s]