Python3 error in unpacking list with fewer variables [a,b,_] in for loop - python-3.x

I am trying to unpack a list with fewer variables and get the following error.
human_prots looks like this:
['9606.ENSP00000482075_HomoSapiens\t10029.XP_007627869.1_CricetulusGriseus,10036.XP_005079789.1_MesocricetusAuratus,10042.XP_006987441.1_PeromyscusManiculatus9986.ENSOCUP00000025621_OryctolagusCuniculus', '']
with open(path_to_homolog_file,'r') as ortho_tab:
ortho_text = ortho_tab.read()
no_genes = []
ortho_list = []
ortho_text.strip()
human_prots = ortho_text.split('\n\n')
for horthos in human_prots:
[hprot,orthos,_] = horthos.split('\t')
[_,hprot] = hprot.split('.')
hprot_info = find_match(db_dict.get('HomoSapiens'),hprot)
if len(hprot_info) > 1 and warning == 'on':
print('WARNING! Multiple matches found for {}: {}'.format(hprot,hprot_info))
[hgene,_] = hprot_info[0].split('\t')
orthos = orthos.split(', ')
line 71, in <module>
[hprot,orthos,*_] = horthos.split('\t')
ValueError: not enough values to unpack (expected at least 2, got 1)
what am I doing wrong?

Related

I'm getting trouble in using numpy and handling list

This code read CSV file line by line and counts the number on each Unicode but I can't understand two parts of code like below.I've already googled but I could't find the answer. Could you give me advice ?
1) Why should I use numpy here instead of []?
emoji_time = np.zeros(200)
2) What does -1 mean ?
emoji_time[len(emoji_list)-1] = 1 ```
This is the code result:
0x100039, 47,
0x10002D, 121,
0x100029, 30,
0x100078, 6,
unicode_count.py
import codecs
import re
import numpy as np
​
file0 = "./message.tsv"
f0 = codecs.open(file0, "r", "utf-8")
list0 = f0.readlines()
f0.close()
print(len(list0))
​
len_list = len(list0)
emoji_list = []
emoji_time = np.zeros(200)
​
for i in range(len_list):
a = "0x1000[0-9A-F][0-9A-F]"
if "0x1000" in list0[i]: # 0x and 0x1000: same nuumber
b = re.findall(a, list0[i])
# print(b)
for j in range(len(b)):
if b[j] not in emoji_list:
emoji_list.append(b[j])
emoji_time[len(emoji_list)-1] = 1
else:
c = emoji_list.index(b[j])
emoji_time[c] += 1
print(len(emoji_list))
1) If you use a list instead of a numpy array the result should not change in this case. You can try it for yourself running the same code but replacing emoji_time = np.zeros(200) with emoji_time = [0]*200.
2) emoji_time[len(emoji_list)-1] = 1. What this line is doing is the follow: If an emoji appears for the first time, 1 is add to emoji_time, which is the list that contains the amount of times one emoji occurred. len(emoji_list)-1 is used to set the position in emoji_time, and it is based on the length of emoji_list (the minus 1 is only needed because the list indexing in python starts from 0).

TypeError: list indices must be integers or slices, not str (using Python 3.7)

TypeError: list indices must be integers or slices, not str (using Python 3.7).
I know why this type error coming 'just means your for loop is saying it cannot iterate index by index over type string arguments,' tried so many different strategies please help.
from operator import itemgetter
balance = 1000
name = "Charles De."
acc_no = "1235621234"
print("Name: ",name, "Account: ", acc_no, "Original Balance: ", "$" +
str(balance))
charges_list = []
charges_dict = []
for charge_string in open("market.txt"):
charge_info_list = charge_string.strip().split(',')
charge_info = dict()
charge_info['vendor'] = charge_info_list[0]
charge_info['date'] = charge_info_list[1]
charge_info['charge'] = charge_info_list[2]
charges_list.append(charge_info)
if charge_info['vendor'] not in charges_dict:
charges_dict[charge_info['vendor']] = list()
charges_dict[charge_info['vendor']].append(charge_info)
charges_sorted_by_date = sorted(charges_list, key=itemgetter('date'))
Getting This Error
====== RESTART: C:\Users\codehax41\Documents\Python\nested_dict_sort.py ======
Name: Charles De. Account: 1235621234 Original Balance: $1000
Traceback (most recent call last):
File "C:\Users\codehax41\Documents\Python\nested_dict_sort.py", line 20, in
<module>
charges_dict[charge_info['vendor']] = list()
TypeError: list indices must be integers or slices, not str
>>>
charges_dict is a list in your code (you have charges_dict = []), but later in the code you're using it as a dict. You should initialize it to an empty dict using either:
charges_dict = {}
Or:
charges_dict = dict()

Error: 'list' object is not callable

I'm trying to make a program that will pick up randomly a name from a file. The user would be asked if he wants to pick up another one again (by pressing 1).
The names can't be picked up twice.
Once picked up, the names would be stocked in a list, written into a file.
When all the names are picked up, the program would be able to restart from the beginning.
I checked other similar problems, but I still don't get it...
from random import *
#import a list of name from a txt file
def getL1():
l1 = open("Employees.txt", "r")
list1 = []
x = 0
for line in l1:
list1.append(line)
x = x+1
list1 = [el.replace('\n', '') for el in list1]
#print("list" 1 :",list)
return list1
#import an empty list (that will be filled by tested employees) during
#execution of the program
def getL2():
l2 = open("tested.txt", "r")
list2 = []
for line in l2:
list2.append(line)
list2 = [el.replace('\n', '') for el in list2]
#print("list 2 :",list2)
l2.close()
return list2
def listCompare():
employees = getL1()#acquire first list from employee file
tested = getL2()#acquire second list from tested file
notTested = []# declare list to hole the results of the compare
for val in employees:
if val not in tested: #find employee values not present in tested
#print(val)
notTested.append(val)#append value to the notTested list
return notTested
def listCount():
x=0
employees = getL1()
tested = getL2()
for val in employees:
if val not in tested:
x = x+1
return x
#add the names of tested employees the the second second file
def addTested(x):
appendFile = open("tested.txt", "a")
appenFile.write(x)
appendFile.write('\n')
appendFile.close()
def main():
entry = 1
while entry == 1:
pickFrom = listCompare()
if listCount() > 0:
y = randint (0, (listCount ()-1))
print ('\n' + "Random Employee to be tested is: ", pickFrom(y), "\n")
addTested(pickFrom[y])
try:
entry = int(input("Would you like to test another employee? Enter 1:"))
except:
print("The entry must be a number")
entry = 0
else:
print("\n/\ new cycle has begun")
wipeFile = open("tested.txt", "w")
print ("goodbye")
main()
The last error that I have is :
Traceback (most recent call last):
File "prog.py", line 78, in <module>
main()
File "prog.py", line 65, in main
print ('\n' + "Random Employee to be tested is: ", pickFrom(y), "\n")
TypeError: 'list' object is not callable
As per the code print pickFrom is a list and when you are referencing it in the print it needs to be called using [ ]. Change it to pickFrom[y]

Issue in python code, unable to find issue

while trying to create a custom map loader from a file, i get the following issue:
"D:\Python 3.4\python.exe" "D:/Games in Python/Game1/game.py"
Traceback (most recent call last):
File "D:/Games in Python/Game1/game.py", line 60, in <module>
game = Game()
File "D:/Games in Python/Game1/game.py", line 4, in __init__
world = World()
File "D:/Games in Python/Game1/game.py", line 23, in __init__
self.load()
File "D:/Games in Python/Game1/game.py", line 54, in load
self.map_data[a][z][y][x] = self.tmp4[x]
IndexError: list index out of range
Process finished with exit code 1
I have tried debugging it myself by printing some parts of the list, and going through the program step by step, but still no success. here's the code:
self.map = open("Data/Saves/test.txt" , "r")
self.map_dat = self.map.read()
self.map.close
self.tmp1 = self.map_dat.split("-")
self.map_data = [None] * 2
for a in range(0, 2):
self.tmp2 = self.tmp1[a].split(">")
self.map_data[a] = [None] * 4
for z in range(0, 4):
self.tmp3 = self.tmp2[z].split("\n")
self.map_data[a][z] = [None] * 100
for y in range(0, 100):
self.tmp4 = self.tmp3[y].split(",")
self.map_data[a][z][y] = [None] * 100
for x in range(0, 100):
self.map_data[a][z][y][x] = self.tmp4[x]
the map file is as follows:
map_lvl0
>
map_lvl1
>
map_lvl2
>
map_lvl3
-
map_lvl0_properties
>
map_lvl1_properties
>
map_lvl2_properties
>
map_lvl3_properties
where map_lvl(0 to 3) a 100*100 grid of zeros seperated by ","
Sorry for giving such a strange description of the map file as i couldn't upload the actual file here
I would really appreciate any help in this matter, any way of making it cleaner, shorter, etc
Your mistake is probably in lines on the outer edges of a grid, aka a tmp2 entry like "\nthe actual data\n", which doesn't start with a row since the whitespace wasn't trimmed off. Or it could be that the properties field doesn't exist out of a numerical matrix.
However this map format is probably not the best way to store your data.
Personally I'd go a binary format for effectiveness or for a JSON file (for readability, and simply parsable with json). Something like:
[
{
"map_name" : "some name",
"map_prop2" : "some value",
...
"map_layout" : [
[0,...,0],
...,
[0,...,0]
]
},
...
]
If you insist with the current format I'd go with a function like this (NOTE: you didn't tell us the format of the properties, so I just kept it as a single string, parse them in the actual solution):
# Returns a dictionairy
# lvls[map_name] -> { id : int, properties : string, grid : int[][] }
def read_map(filename):
lvls = {}
with open(filename, "r") as f:
lvls_data, lvls_props = f.read().split("-")
lvls_data = [ s.strip() for s in lvls_data.split(">") ]
lvls_props = [ s.strip() for s in lvls_props.split(">") ]
assert(len(lvls_data) == len(lvls_props))
for i in range(len(lvls_data)):
# I had no idea how to parse the properties, since I don't know the
# format. So I kept it plaintext, do actually parse them
data, properties = lvls_data[i], lvls_props[i]
grid = [ [ int(point) for point in line.split(",") ] for line in data.split("\n") ]
# assert all dimensions are in order
assert(len(grid) == 100)
assert(all(len(grid[i]) == 100 for i in range(100)))
lvls["map%i" % i] = { 'id' : i, 'properties': properties, 'grid' : grid}
return lvls
NOTE I had no way to properly test this, so use with caution

struct.pack in Python3 got struct.error: required argument is not an integer

I'm doing a zipping func of this:
open_file = open(file_path,'rb')
open_save = open(save_path,'wb+')
try:
open_read = open_file.read()
data = zip_data(open_read)
head_xis = b'XIS'
head_version = bytes(0)
head_type1 = bytes(1)
head_type2 = bytes(1)
head_en_type = bytes(0)
head_com_type = bytes(1)
head_sour_len = len(open_read)
# try:
md5 = hashlib.md5()
md5.update(open_read)
head_md5 = md5.digest()
print("byteeeeee")
# except:
# head_md5 = None
randoms = str(uuid.uuid1()).split('-')[0]
head_random = bytes(randoms,encoding = "utf-8")
print(head_md5)
print(head_random)
head_resour_len= len(data)
print(type(head_xis))
print(type(head_version))
print(type(head_type1))
print(type(head_type2))
print(type(head_en_type))
print(type(head_com_type))
print(type(head_sour_len))
print(type(head_md5))
print(type(head_random))
print(type(head_resour_len))
head = struct.pack('3sBBBBBI16s8sI',
head_xis,
head_version,
head_type1,
head_type2,
head_en_type,
head_com_type,
head_sour_len,
head_md5,
head_random,
head_resour_len
)
open_save.write(head)
# except Exception as e:
# print("eeeee" + str(e))
# return False,str(e)
# else:
# open_save.write(data)
# return True,''
finally:
open_file.close()
open_save.close()
and it shows exception and print like below:
byteeeeee
b'\xf9\xf4\xf2\xcb\xbfM\x11\xb5\xeeNP/\x02H\xebK'
b'f9f33502'
class 'bytes'
class 'bytes'
class 'bytes'
class 'bytes'
class 'bytes'
class 'bytes'
class 'int'
class 'bytes'
class 'bytes'
class 'int'
Traceback (most recent call last):
File "entrance.py", line 52, in startProcess
Helper.processCombine(self.selectedVer,False)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/Helper.py", line 86, in processCombine
itemConf.get(version,suffix),True,True)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/coluaco.py", line 514, in process
compress(build_dir,zip_dir,filter_file)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/coluaco.py", line 400, in compress
zfile = zip_file(src_file_path,save_path)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/coluaco.py", line 131, in zip_file
head_resour_len
struct.error: required argument is not an integer
I have tried to print types of arguments,
and it seems to fit 3sBBBBBI16s8sI correctly
I'm confused by what arg that performs this exception
In structure formating string "B" for bytes need variable type 'int', that is main problem. So instead of head_type1 = bytes(1) use head_type1 = 1
Here given below code gives same error.
Problem:
n = bytes(2)
x = struct.pack("B", n)
Solution:
n = 2
x = struct.pack("B", n)
Suggestion:
Use Byte Orders like '=', while dealing with integers like 'I'.

Resources