【问题标题】:Problems with elements in a list列表中元素的问题
【发布时间】:2019-05-08 02:30:11
【问题描述】:

我有一个列表 = ['0.2 0.2 0.3 0.2 0.3', '0.4 0.3 0.1 0.5 0.1', '0.3 0.3 0.5 0.2 0.4', '0.1 0.2 0.1 0.1 0.2'] 我需要用逗号分隔像这样的元素: '0.2, 0.2, 0.3, 0.2, 0.3'... 我正在解析一个文件,但我卡在了这一步。

我试过这个:

with open('profileKmer.txt') as f:

    lines = f.read().splitlines()
    prof = [x.strip(' ') for x in lines[4:8]]
    profile = []
    for element in prof:
        if element.startswith('0'):
            profile.extend(element.split(','))
    print(profile)

但我没有得到我想要的。

数据如下:

headline
input
ACCTGTTTATTGCCTAAGTTCCGAACAAACCCAATATAGCCCGAGGGCCT
5
0.2 0.2 0.3 0.2 0.3 
0.4 0.3 0.1 0.5 0.1
0.3 0.3 0.5 0.2 0.4
0.1 0.2 0.1 0.1 0.2

我非常感谢任何见解。

【问题讨论】:

  • 您可以使用内置字符串split' ' 参数将单个空格拆分为列表。目前还不清楚您是否希望输出是 python 列表或用逗号分隔数字的字符串
  • try [','.join(s.split()) for s in l] 其中 l 是您的列表..(请不​​要使用列表作为变量名称)
  • foo.split() 然后",".join(foo) 怎么样。这是假设您想要一组逗号分隔的字符串,否则您在 foo.split() 之后完成,如果您希望它们都在一个列表中,则可能使用 list.extend
  • 我想要数据 = ['0.2, 0.2, 0.3, 0.2, 0.3', '0.4, 0.3, 0.1, 0.5, 0.1', '0.3, 0.3, 0.5, 0.2, 0.4', '0.1, 0.2, 0.1, 0.1, 0.2'] 因为它们将用作字典中的值。
  • 我不使用列表作为列表的名称。那只是为了显示输入。我真的很抱歉,但我无法正确输入。 line0 首行,line[1] 编号和 line[4:8] 一种数组 0.2, 0.2, 0.3, 0.2, 0.3...谢谢

标签: python


【解决方案1】:

你可以试试这个:

def trial(list):
  new_list = []

  for item in list:
      temp_item = ",".join(item.split())
      new_list.append(temp_item)

  print(new_list)
  # Result:
  # ['0.2,0.2,0.3,0.2,0.3', '0.4,0.3,0.1,0.5,0.1', '0.3,0.3,0.5,0.2,0.4', '0.1,0.2,0.1,0.1,0.2']
if __name__ == '__main__':
  list = ['0.2 0.2 0.3 0.2 0.3', '0.4 0.3 0.1 0.5 0.1', '0.3 0.3 0.5 0.2 0.4', '0.1 0.2 0.1 0.1 0.2']
  trial(list)

【讨论】:

  • @PauloSergioSchlogl 如果答案有助于解决您的问题,请接受答案。最好的问候
猜你喜欢
  • 2021-12-30
  • 2020-09-03
  • 2020-07-19
  • 2021-05-10
  • 2021-12-30
  • 2018-01-31
  • 2011-04-02
  • 1970-01-01
相关资源
最近更新 更多