减去列表中的两个值

时间:2019-11-16 14:54:22

标签: python python-3.x list subtraction

my_list = [['chr1', 65419, 65433], ['chr1', 65520, 65573], ['chr1', 69037, 71585], ['chr1', 69055, 70108], ['chr1', 137621, 139379],['chr2', 65419, 65433], ['chr2', 65520, 65573], ['chr2', 69037, 71585], ['chr3', 69055, 70108]]

列表中将包含字符串“ chr1”,“ chr2”,“ chr3”。我想减去每个字符串的索引2-1的值,并获取'chr1','chr2','chr3'的总值

示例 在前两个字符串中(65433-65419)应该减去,然后在(65573-65520)中加上,因为它们都包含'chr1'。所有列表均应如此,最终结果应如下 'chr1'总计= x_value,'chr2'总计= y_value,'chr3'总计= x_value

我是一种新的python。有人可以为此建议一个代码。

4 个答案:

答案 0 :(得分:3)

对于大型列表,您可以这样做(不匹配硬编码的字符串):

from collections import defaultdict
my_list = [['chr1', 65419, 65433], ['chr1', 65520, 65573], ['chr1', 69037, 71585], ['chr1', 69055, 70108], ['chr1', 137621, 139379],['chr2', 65419, 65433], ['chr2', 65520, 65573], ['chr2', 69037, 71585], ['chr3', 69055, 70108]]
result = defaultdict(int)
temp = [{i[0]:i[2]-i[1]} for i in my_list]
for di in temp:
    result [ list(di.keys())[0] ] += list(di.values())[0]
for i,v in result.items():
    print(f"{i} total = {v}")

答案 1 :(得分:2)

numpy.savetxt

答案 2 :(得分:1)

my_list = [['chr1', 65419, 65433], ['chr1', 65520, 65573], ['chr1', 69037, 71585], ['chr1', 69055, 70108], ['chr1', 137621, 139379],['chr2', 65419, 65433], ['chr2', 65520, 65573], ['chr2', 69037, 71585], ['chr3', 69055, 70108]]
mylist1=list()
mylist2=list()
mylist3=list()

for i in my_list:
    if i[0]=='chr1':
        mylist1.append(i[2]-i[1])
    elif i[0]=='chr2':
        mylist2.append(i[2]-i[1])
    elif i[0]=='chr3':
        mylist3.append(i[2]-i[1])

print("chr1:",sum(mylist1))
print("chr2:",sum(mylist2))
print("chr3:",sum(mylist3))

sum已经是要使用的预定义函数。

现在,如果您还有更多的时间:

my_list = [['chr1', 65419, 65433], ['chr1', 65520, 65573], ['chr1', 69037, 71585], ['chr1', 69055, 70108], ['chr1', 137621, 139379],['chr2', 65419, 65433], ['chr2', 65520, 65573], ['chr2', 69037, 71585], ['chr3', 69055, 70108]]
chrset=set()
for i in my_list:
    chrset.add(i[0])

res = dict.fromkeys(chrset, 0)

for i in my_list:
    res[i[0]]=res[i[0]]+i[2]-i[1]
print(res)

对于python新手来说,创建一组chr1,chr2,.....然后创建字典并直接对其进行操作会容易得多。

答案 3 :(得分:1)

您可以使用字典来保存键-值对,并在具有相同键的更多列表更新时对其进行更新。

my_dict=dict()
for entry in my_list:
    if entry[0] in my_dict:
        my_dict[entry[0]]+=entry[2]-entry[1]
     else:
         my_dict [entry[0]]=entry[2]-entry[1]

无论您拥有什么键,它都可以工作(不限于示例中的三个键)