ValueError while Merging Lists in Python - python

I'm trying to get one array out of several arrays in python 2.7
I found on the internet that this is done simply by adding both lists:
lista = [1,2,3]
listb = [3,4,5]
listc = lista + listb
In my case my first list i empty and the next list has 99 elements.
My code looks like this
data_complete = []
for i in range(1, numberOfFiles+1):
data = getDataFromFile(i)
data_complete = data_complete + data
The last line of code does not work, it returns the error:
data_complete = data_complete + data
ValueError: operands could not be broadcast together with shapes (0) (99)
I would be glad if someone can solve this.
Kind Regards

You can use append method if its a single item
data_complete.append (data)
You can use extend method if data itself is a list
data_complete.extend (data)

It looks like getDataFromFile is returning a numpy array, rather than a list. In this case, + will use the array's concatenation routine, which has some extra requirements compared to lists (and returns another array). You can use the list extend method instead to get around this:
data_complete = []
for i in range(1, numberOfFiles+1):
data = getDataFromFile(i)
data_complete.extend(data)

just append the data to your list
for example:
evens = []
for i in xrange(10):
if i%2 == 0:
evens.append(i)
at the end of this program evens will equal [2,4,6,8]

Related

Is it possible to use the same slice notation in both a list and an element to get the same result?

I want to get the element in the last index of a list, but sometimes the last index is a list, in this case I want the first element in the nested list.
#list in moment 1:
Lm1 = [1,2,3,4]
#list in moment 2:
Lm2 = [1,2,3,4,[1,2,3]]
I can just use an if for this.
#Option1:
def if_list(lastposition):
if isinstance(lastposition, list):
return list[0]
else:
return lastposition
element = if_list(Lm1[-1])
do whatever
Or if I want to do the same operation in both cases I could buit the list like this and use the same slice notation. It will give the element I want.
#Option2:
Lm1 = [[1],[2],[3],[4]]
Lm2 = [[1],[2],[3],[4],[1,2,3]]
Lm1[-1][0]
Lm2[-1][0]
Is there a way to do this using something similar to slice notation that will work in both cases (when index is list and when index is not list) or a simple one liner?
Something like:
#Lm1[-1:][:]...
The problem is that I don't know if its more time eficient to just build the list
like Option2 and use the same slice notation or to use the if cause everytime like Option1.
I'm using pythom 3.7, don't know much about older versions.
I created a test bench to compare using try-except and isinstance to see which is faster and here are the results.
Option2:
Parsing all data to a list doesn't seem like an efficient way to me. :/
import time, statistics
Lm2 = [1,2,3,4,1,2,3]
t = []
for y in range(4):
s = time.time()
for i in range(100000):
if isinstance(Lm2[-1], list):
x = Lm2[-1][0]
else:
x = Lm2[-1]
t.append(time.time() - s)
print(statistics.mean(t))
Lm2 = [1,2,3,[4,1,2,3]]
t = []
for y in range(4):
s = time.time()
for i in range(100000):
try:
x = Lm2[-1][0]
except Exception:
x = Lm2[-1]
t.append(time.time() - s)
print(statistics.mean(t))
Lm2 = [1,2,3,[4,1,2,3]]
t = []
for y in range(4):
s = time.time()
for i in range(100000):
x = Lm2[-1][0] if type(Lm2[-1]) is list else Lm2[-1]
t.append(time.time() - s)
print(statistics.mean(t))
The results as follow in order
# When the last element is a list
# 0.024208366870880127
# 0.011709034442901611
# 0.03266298770904541
# When the last element is an int
# 0.02896404266357422
# 0.015629112720489502
# 0.03452497720718384
According to the data I got, using try-except will be always faster
You can do a one liner like this if you want:
#list in moment 1:
Lm1 = [1,2,3,4]
#list in moment 2:
Lm2 = [1,2,3,4,[1,2,3]]
def test(test_list):
return test_list[-1][0] if type(test_list[-1]) is list else test_list[-1]
print(test(Lm1))
print(test(Lm2))
Check if the last value is a list, if it is, return the first value, otherwise give you the last element of your list.

Getting value from a list corresponding to another list

I have a list containing:
NewL = [(1.1,[01,02]),(1.2,[03,04]),(1.3,[05,06])]
and i used enumerate to obtain the list as above where the square brackets containing [01,02],[03,04] and [05,06] are generally obtained from another list. I'll show it just in case:
L = [[01,02],[03,04],[05,06]]
and initially the output list is just:
OutputList = [1.1,1.2,1.3]
i used enumerate on both of this list to get what i have as the first list i've written above.
The problem i'm facing now is, let's say i want to only output the value for [05,06] which is 1.3 from the NewL. How would i do that? I was thinking of something like:
for val in NewL:
if NewL[1] == [05,06]:
print NewL[0]
but it's totally wrong as cases might change where it's not necessary always be [05,06] as it can be obtaining value for [03,04] and [01,02] too. I'm pretty new using enumerate so I'll appreciate any help for this.
The for loop should like this:
for val in NewL:
if val[1] == [5,6]:
print val[0]
It will print 1.3
I'm not sure I understand the question, so I will extrapolate what you need:
Given your 2 intial lists:
L = [[01,02],[03,04],[05,06]]
OutputList = [1.1,1.2,1.3]
you can generate your transformed list using:
NewL = list(zip(OutputList, L))
then, given 1 item from L, if you want to retrieve the value from OutputList:
val = [x for x, y in NewL if y == [05,06]][0]
But it would be a lot easier to just do:
val = OutputList[L.index([05,06])]
Note that both those expressions will raise an IndexError if the searched item is not found

Python error: Index out of range

seq_sum = []
for i in range(len(sequence)):
seq_sum[i] = sequence[i] + inv_sequence[i]
print (seq_sum)
When I try to run this code it return an error: list assignment index out of range. How can I fix the problem?
sequence and inv_sequence are arrays of integers.
seq_sum[i] will raise an IndexError as the seq_sum list is empty. You should use append instead:
seq_sum = []
for i in range(len(sequence)):
seq_sum.append(sequence[i] + inv_sequence[i])
print(seq_sum)
You can achieve the same result with a prettier code using list comprehension:
seq_sum = [seq_elem + inv_elem for seq_elem, inv_elem in zip(sequence, inv_sequence)]
You could also use map but some would argue its readability:
import operator
seq_sum = list(map(operator.add, sequence, inv_sequence))
You've declared seq_sum to be an empty list. You then try and index in a position other than 0 which results in an IndexError.
Expanding a list to make it larger is essentially done with appending, extending or slice assignments. Since you sequentially access elements, seq_num.append is the best way to go about this.
That is:
seq_sum[i] = sequence[i] + inv_sequence[i]
Should be instead changed to:
seq_sum.append(sequence[i] + inv_sequence[i])

Variation of suffix array in python

I'm relatively new to computer science, and I'm learning how to code in python. I'm trying to figure out how to make a function that takes a list and returns a list of suffixes from the inputted list, in order from shortest length to longest length. For example, entering
[3,4,2,-9,7,6,1]
to the function would return
[[],[1],[6,1],[7,6,1],[-9,7,6,1],[2,-9,7,6,1],[4,2,-9,7,6,1],[3,4,2,-9,7,6,1]]
I've tried several approaches, but so far I'm not having much luck. Here is what I have so far:
def h(m):
newlist = []
x = 0
y = (len[m])-1
while x in range(y):
sublist = []
sublist = sublist + m[x:y]
newlist.append(sublist)
x += 1
return new list
When I try to run the function by entering something like
a = [3,4,2,-9,7,6,1]
h(a)
I get an error:
Traceback (most recent call last):
File "<pyshell#239>", line 1, in <module>
h(a)
File "<pyshell#238>", line 4, in h
y = (len[m])-1
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
My objective with this bit of code was simply to create a the list of suffixes without sorting them by length. After I figure out how to create this new list I will add the sorting bit of the code. Keep in mind this is not a homework assignment. Any help would be greatly appreciated!
Possible solution is using list comprehension:
[l[i:] for i in range(len(l), -1, -1)]
This code uses slicing and list comprehension to simply return a list of slices from the end. Using your code, small modification is required - len is a function and not a dictionary, therefore you need to use the call operator () instead of subscript operator [].
y = len(m) - 1
That will not yield correct result though, because you will not get the last suffix and empty suffix. In order to cover these two, you will need to modify y or the loop to cover them
y = len(m) + 1
or better
while x in range(y + 1):
use parenthesis to get the length of the list:
y = len(m) - 1
Your error is in your len:
(len[m]) - 1
len is a function, and you can't index or slice or the what not. Do this instead:
y = len(m) - 1
There's also one other error:
return new list
Should be: (You can't have spaces in variables)
return newlist

Python string extraction from array of strings

I am having trouble figuring out the following:
Suppose I have a list of strings
strings = ["and","the","woah"]
I want the output to be a list of strings where the ith position of every string becomes a new string item in the array like so
["atw","nho","dea","h"]
I am playing with the following list comprehension
u = [[]]*4
c = [u[i].append(stuff[i]) for i in range(0,4) for stuff in strings]
but its not working out. Can anyone help? I know you can use other tools to accomplish this, but i am particularly interested in making this happen with for loops and list comprehensions. This may be asking a lot, Let me know if I am.
Using just list comprehensions and for loops you can:
strings = ["and","the","woah"]
#Get a null set to be filled in
new = ["" for x in range(max([len(m) for m in strings]))]
#Cycle through new list
for index,item in enumerate(new):
for w in strings:
try:
item += w[index]
new[index] = item
except IndexError,err:
pass
print new
My idea would be to use itertools.izip_longest and a list comprehension.
>>> from itertools import izip_longest
>>> strings = ["and","the","woah"]
>>> [''.join(x) for x in izip_longest(*strings, fillvalue='')]
['atw', 'nho', 'dea', 'h']
Try
array = ["and","the","woah"]
array1 = []
longest_item = 0
for i in range(0,3): #length of array
if len(array[i]) > longest_item:
longest_item = len(array[i]) #find longest string
for i in range(0,longest_item):
str = ""
for i1 in range(0,3): #length of array
if len(array[i1]) < longest_item:
continue
str += array[i1][i:i+1]
array1.append(str)
I didn't actually try this code out, I just improvised it. Please leave a comment ASAP if you find a bug.

Categories

Resources