Getting TypeError: list indices must be integers when using list[:,colIndex] to get column data as list - jython-2.7

I have a 2D list (a list of lists) and am trying to use the notation list[:,colIndex] to pull out a single column's data into another list, but I'm getting a TypeError: list indices must be integers error.
for example:
lst = [[1,2,3],[10,12,13]]
lst[:,0]
Returns:
Traceback (most recent call last):
File "<input>", line 2, in <module>
TypeError: list indices must be integers
I don't understand...
Edit:
Running this in Python 3.9 gives me:
TypeError: list indices must be integers or slices, not tuple

It would seem that the [:,colIndex] syntax isn't supported by lists and is available to numpy arrays only :(
However I can use: list(zip(*lst))[colIndex] instead from this answer https://stackoverflow.com/a/44360278/1733467

Related

how to put variable in python defaultdict call

In a python defaultdict object (like obj1), I can call obj1['hello','there'] and get item. but when the input list is variable (for example: input_list), how I can call obj1[input_list]?
when I call obj1[input_list], python raise this error:
TypeError: unhashable type: 'list'
when use obj1[*input_list], python returns:
SyntaxError: invalid syntax
So what is the correct way to put list as variable in defaultdict?
The error TypeError: unhashable type: 'list' states that list is not hashable, but a dict always needs a hashable key!
If you test my_normal_dict[2,3] you can see that it actually treats these two numbers as the tuple (2,3) because the error is KeyError: (2, 3), so you need to input a hashable iterable like a tuple.
For example, my_dict[tuple(my_list)] should work, as long as all the elements of the tuple itself are hashable!
Note though: If your list is large, it may be relevant that this needs to copy all elements into a tuple.

TypeError: type.__new__() argument 2 must be tuple, not str

I get the following error when I run the piece of code below. I can clearly print the value of *strs on screen, which appears as string. But, when I do type(*strs), it throws TypeError: type.__new__() argument 2 must be tuple, not str. Can someone explain this behaviour?
strs = ["flower","flood","flight"]
print(*strs)
print(type(strs))
print(type(*strs))
Output:
Traceback (most recent call last):
print(type(*strs))
TypeError: type.__new__() argument 2 must be tuple, not str
flower flood flight
<class 'list'>
Process finished with exit code 1
The asterix operator in '*strs' unpacks the iterms in 'strs', which is a series of three strings. Your code ran into trouble when it tried to send those strings to the type() command, where type() was initialized by its __ new__() magic method.
type() has two forms:
1.) type(object) where the 'object' is an instance of some class.
2.) type(name, bases, dictionary) where 'bases' is a tuple that itemizes base classes, and a dictionary that contains definitions of base classes.
In your code, the use of the unpacking operation, *strs, resulted in type() being sent three arguments, so it was expecting a name, a tuple, and a dictionary. What it, and then __ new()__ got was three strings: A name (it received 'flower'), then another string, "flood", where it wanted a tuple. Here python threw the error and never made it to the third string, 'flight'.
We can duplicate the error with:
print(type("a","b","c"))
We can also see that either one or three (but not two) arguments were expected, with:
print(type("a","b"))
while the following command works just fine:
print(type("a"))
If you want to see the type of each member of *strs, first let it unpack to a list, then iterate through that list, printing the type of each member as you go.
mylist = [*strs]
for elm in mylist:
print(type(elm))
Does this answer the question of what caused that behavior and the error?

How do I nest a For Loop w/ IF statement to return a new list?

Can the return in an If statement append a list?
Is python aware that the list elements are actually dictionaries and that 'sublist' iterates over those elements?
I tried being data type specific after For previously and that doesn't help
Is the If statement actually accessing the dictionary?
My code:
In[1]: restaurants = [fork_fig, frontier_restaurant]
In [2]: def open_restaurants(restaurants):
for sublsit in restaurants:
op=[]
if sublist.get('is_closed')==False:
op.append(sublist.get('name'))
passed through their code:
In [1]: len(open_restaurants(restaurants))
Out[2]: NameErrorTraceback (most recent call last)
<ipython-input-14-e78afc732a29> in <module>
----> 1 len(open_restaurants(restaurants)) # 1
<ipython-input-13-56ad484d6dd9> in open_restaurants(restaurants)
2 for sublsit in restaurants:
3 op=[]
----> 4 if sublist.get('is_closed')==False:
5 op.append(sublist.get('name'))
6
NameError: name 'sublist' is not defined
and next: I think this is because the list i defined is not populating with the correct information.
In[3]: open_restaurants(restaurants)[0]['name'] # 'Fork & Fig'
Out[4]:TypeErrorTraceback (most recent call last)
<ipython-input-15-bf5607d088f4> in <module>
----> 1 open_restaurants(restaurants)[0]['name'] # 'Fork & Fig'
TypeError: 'NoneType' object is not subscriptable
Your indentation may be not correct
You didn't return the result (probably return op) in your function
The problem here was that I was entering too much information.
The code that ended up working perfectly was as follows:
def open_restaurants(restaurants):
op=[]
for sublist in restaurants:
if sublist['is_closed']==False:
op.append(sublist)
return op
I separated op list from the for loop.
Previously, the NameError said sublist was not defined, yet it was
defined by including it in the For; to fix I removed .get() and
replaced it with list form x[].
Last, separated return from the .append() function.

using Python 3.7, how to use of numpy complex with an array of values

I am new to Python, so I apologize ahead of time if this question is too basic.
Say I have a complex value 50+ j(10 w), where w is an array of frequencies, for example,
import numpy as np
w=2*np.pi*np.linspace(1800e6,2400e6,100)
how do I use np.complex to calculate the complex value for each value in the w array (or any other way to accomplish this)?
In Matlab, I could do
z = 50 + i.*w.*10
(although I don't think I would need to since everything else is a scalar in the equation, but this helps show what I want to do --element by element multiplication).
Anyway, when I try:
z=np.complex(50,10*w)
I get the following error:
Traceback (most recent call last):
File "<ipython-input-14-a78f7e2cf118>", line 1, in <module>
z=np.complex(50,10*w)
TypeError: only size-1 arrays can be converted to Python scalars'
I appreciate any help. Thank you.

reading a csv file into a Networkx graph in python 3.5

I am following this tutorial: graph tutorial on my own data file. but I am getting stuck on the last bit. the code seems to throw:
(most recent call last)<ipython-input-193-7227d35394c0> in <module>()
1 for node in links: #loops through each link and changes each dictionary to a tuple so networkx can read in the information
2 edges = node.items()
----> 3 G.add_edge(*edges[0]) #takes the tuple from the list and unpacks the tuples
4
5 nx.draw(G)
TypeError: 'dict_items' object does not support indexing
is there a fix? I'm sort of stuck.
This is probably python-2 only compatible code.
In python 2, dict.items() returns a list of tuples (key, value) as opposed to dict.iteritems()
In python 3, dict.iteritems() has been removed, and dict.items() returns an iterator.
So you have to explicitly convert it to list to get access to the elements by index:
edges = list(node.items())

Resources