python - 更改 python 中列表列表的代码

标签 python

我有一个名为 mylist 的列表:

mylist = ['chr1', '+', '11873', '14409', 'DDX11L1']

为了进行一些操作,我有以下代码:

left_num = int(mylist[2]) 
right_num = int(mylist[3])
diff= (right_num-left_num)/100 
last_column = mylist[4] + "_part" 


with open("output.txt", "w+") as op_file: 
    op_file.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(mylist[0], mylist[1], left_num, right_num, mylist[4], last_column + str(1)))
    for num in range(2,101):
        temp = int(right_num) 
        right_num = int(right_num + diff) 
        op_file.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(mylist[0], mylist[1], temp, right_num, mylist[4], last_column + str(num)))

此代码返回一个名为 output.txt 的文件,其中包含 100 行。我正在尝试将此代码用于列表列表,如下例所示:

mylist = [['chr1', '+', '11873', '14409', 'DDX11L1'], ['chr1', '-', '14361', '16765', 'WASH7P']]

我正在尝试将上面的代码用于此列表列表,如果我设法这样做,我将获得一个包含 200 行的文件(每个子列表 100 行)。我仅使用 for 循环尝试了以下代码,但它不起作用。你知道我如何将上面的代码更改为列表列表:

left_num = []
for i in new:
    left_num.append(int(i[2]))


right_num = []
for i in new:
    right_num.append(int(i[3]))


diff = []
for i in new:
    s = (int(i[3])- int(i[2]))/100
    diff.append(s)


last_column = []
for i in new:
    d = i[4] + "_part"
    last_column.append(d)


for x in mylist:
    with open("output.txt", "w+") as op_file: 
        op_file.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(x[0], x[1], left_num, right_num, x[4], last_column + str(1))) 
        for num in range(2,101):
            temp = int(right_num) 
            right_num = int(right_num + diff) # calc difference
            op_file.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(x[0], x[1], temp, right_num, x[4], last_column + str(num)))

最佳答案

在第一个示例中:

这些变量是整数

left_num = int(mylist[2]) 
right_num = int(mylist[3])

在第二个示例中:

left_num = []

for i in new:
    left_num.append(int(i[2]))


right_num = []
for i in new:
    right_num.append(int(i[3]))

你不能像这样在“write”中使用列表(2次,1在第二个for循环之前,2.在第二个for循环中):

op_file.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(x[0], x[1], temp , right_num, x[4], last_column + str(num)))

将它们称为(或取任意值):

op_file.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(x[0], x[1], temp ,right_num[1],x[4],last_column + str(num)))

`

关于python - 更改 python 中列表列表的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53517508/

相关文章:

python - Pandas 删除带有时间值的行

python - 从 MEDIA_ROOT 下载不工作

python - 自动更新python脚本

python - 使用不同的环境变量创建对象

javascript - child_process spawnSync 使用 for 循环迭代 python stdout 结果

Python crypt 包 : Can type extra characters in password

python - 迁移到 Python27 后的数据存储 'Response too large error'

python - 如何安装py2app

javascript - 用于将任何语言的代码解析为 AST 的 Python 库?

python - 使用 SageMaker Lifecycle 配置在启动时执行 jupyter notebook