繁体   English   中英

如何在 python 中对带有多个分隔符的行使用 split 和 strip 在 linux 上

[英]how to use split and strip in python for lines with multiple delimiters on linux

我有一个像

a= [(0.11004363790442408, '0 22'),
    (1.0003303788789184, '1 7'),
    (0.9427256865065468, '15 23'),
    (0.3508626679066326, '8 21'),
    (1.0815767762687958, '5 27'),
    (0.2889125295483047, '19 26'),
    (0.9294135566237669, '4 10')]

我想访问如下单个实体作为第一个括号的示例。 这里只显示了 7 个条目; 在实际情况下,这些是数百万!

ID[0]= 0.11004363790442408
ID[1]=0
ID[2]=22

我写了类似的东西

entities=len(a)
for data in range(entities):
 lineContent=a.strip(' ').split(' ').split(',')
 print lineContent
 ID[0]= lineContent [0]
 ID[1]= lineContent [1]
 ID[2]= lineContent [2]

所有条目都应该有一些循环,所以我在该范围内使用了for循环。 有什么建议?

还请详细说明拆分,以便可以对其进行修改。

entities = len(a)

for data in range(entities):
    ID = []
    ID.append(a[data][0])
    ID.extend(a[data][1].split(' '))
    print("ID[0] = {0}\nID[1] = {1}\nID[2] = {2}\n".format(ID[0], ID[1], ID[2]))

不知道这是否是你想要的。

这是一项简单的任务,有多种方法可以解决。 这是一个:

a= [(0.11004363790442408, '0 22'),
    (1.0003303788789184, '1 7'),
    (0.9427256865065468, '15 23'),
    (0.3508626679066326, '8 21'),
    (1.0815767762687958, '5 27'),
    (0.2889125295483047, '19 26'),
    (0.9294135566237669, '4 10')]


# no iterator, just the list elements
for lst in a:
    # make a new list containing only the float at first
    ID = [lst[0]]
    # extend the list with the two tuple values cast to int 
    ID.extend(int(x) for x in lst[1].split(" "))
    print ID

另一个(基本上相同但更短):

for lst in a:
    ID = [lst[0]] + [int(x) for x in lst[1].split(" ")]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM