如何在python中为字符串数组赋值多个值

时间:2023-01-24 21:43:04

I'm reading a file line by line and am trying to parse a part of each line and do stuff with it. the Info that I'm trying to parse are 25 strings

我正在逐行读取一个文件,我正在尝试解析每一行的一部分并用它做一些事情。我正在尝试解析的信息是25个字符串

I was trying to do

我试图这样做

for i in info:
  Consequence=i[0]    
  IMPACT=i[1]
  .
  .
  HGNC_ID = i[24]

but obviously there's a better way of doing this. I tried making a list of all the strings and initialize them as empty strings, and then did:

但显然有更好的方法可以做到这一点。我尝试制作所有字符串的列表并将它们初始化为空字符串,然后执行:

                  for counter,val in enumerate(info_list):

                    try:
                        val=i[counter]
                        break
                    except:
                        val=""

where

info_list=(Allele,Consequence...)

That doesn't work though, it prints empty strings and counter is always zero, even though the length of info_list is 25.

这不起作用,它打印空字符串,计数器始终为零,即使info_list的长度为25。

What would be the best way to assign those values? (keep in mind that some "infos" might have 23 or 24 values in the array, in that case I would want to assign an empty string to the missing values, the missing values would only be at the end so there is no confusion as to which variables are missing)

分配这些值的最佳方法是什么? (请记住,某些“infos”可能在数组中有23或24个值,在这种情况下,我希望为缺失值分配一个空字符串,缺少的值只会在结尾处,因此不会产生混淆缺少哪些变量)

Let me know if I can add more information!

如果我可以添加更多信息,请告诉我们!

Thanks! :)

1 个解决方案

#1


0  

There does not seem to be much wrong with your first version of the code. I don't know why you think there "obviously" should be a better way.

您的第一个代码版本似乎没有太大问题。我不知道为什么你认为“显然”应该是一个更好的方法。

One thing you can do to make this a little clearer is:

你可以做的一件事是让它更清晰一点:

if len(info) == 25:
    Consequence, IMPACT , . . ., HGNC_ID  = info
elif len(info) == 24:
    Consequence , IMPACT , . . ., HGNC_ID = info + ''

But I doubt if that will make it much better.

但我怀疑这是否会使它变得更好。

What you might want to consider is not using variables but a hash table or a named tuple for the values you read from the line.

您可能要考虑的不是使用变量,而是使用哈希表或命名元组来表示从行中读取的值。

#1


0  

There does not seem to be much wrong with your first version of the code. I don't know why you think there "obviously" should be a better way.

您的第一个代码版本似乎没有太大问题。我不知道为什么你认为“显然”应该是一个更好的方法。

One thing you can do to make this a little clearer is:

你可以做的一件事是让它更清晰一点:

if len(info) == 25:
    Consequence, IMPACT , . . ., HGNC_ID  = info
elif len(info) == 24:
    Consequence , IMPACT , . . ., HGNC_ID = info + ''

But I doubt if that will make it much better.

但我怀疑这是否会使它变得更好。

What you might want to consider is not using variables but a hash table or a named tuple for the values you read from the line.

您可能要考虑的不是使用变量,而是使用哈希表或命名元组来表示从行中读取的值。