So in Python, I have a matrix as follows:
theMatrix = [["String", "0"],["String2", "1"]]
And I would like to convert all numbers at index 1 of each list to an integer.
Result:
theMatrix = [["String", 0],["String2", 1]]
This needs to work for more than just the two lists:
eg. theMatrix = [["String", 0],["String2", 1],["String3", 2],["String4", 3]]
please elaborate on programming language and will there be more element in the inner list or they are always tuples? u want to convert every integers in string format to int or just the 2nd item in inner list? what is the intention or usage of this data structure. what you may need to consider is a dictionary or hash table. Just give a thought it will fit for ur solution.
For python language and you may have more elements in inner list and always position 1 has to be changed, then the following code may help
for innerList in theMatrix:
if len(innerList) > 1:
value = int(innerList[1])
innerList[1] = value if value >= 0 else 0
theMatrix = [["String", '0'],["String2", '1'],["String3", '2'],["String4", '3']]
#iterate the list of lists and convert the int string to int.
[[e[0],int(e[-1])] for e in theMatrix]
Out[222]: [['String', 0], ['String2', 1], ['String3', 2], ['String4', 3]]
Related
a=[2]
a.append(3)
print (a)
result is [2, 3].
I want to have a output 23 instead of [2,3]. Any suggestions?
When you do something like a = [2] in Python, it creates a list out of it with one element 2 in the list.
You seemingly want string operations. There are two ways to do this. Firstly,
a = '2'
a = a + '3'
print (a)
Another way, probably the one which you're looking for, is converting the list into a string, as follows.
a = [2]
a.append(3)
b = ''.join(str(x) for x in a)
print (b)
Here is a brief explanation of the second approach:
You forcibly typecast each element of the list a to string, and then use join method to convert the list to string. Essentially, first the list [2, 3] is converted to ['2', '3'] and then join is used.
Edit:
Another approach, to better explain what I said above,
a = [str(2)]
a.append(str(3))
b = ''.join(a)
print (b)
Since the numbers are stored as ints instead of strings it makes it slightly more difficult as you will need to cast them to strings.
a=[2]
a.append(3)
print("".join(str(x) for x in a))
This will give your desired output. If you want the output to be an int then you can just cast it back.
What I have is following code snippet:
a = ["2013-11-20,29,0,0", "2013-11-20,3,0,2"]
where a[1] is the a[1]th 5 minute in a day, a[3] and a[4] are number of counts.
I want to sort this by the first two elements. But when I use sort, a[0] always comes first. In fact, I want a[1] to come first. How should I do this?
I have tried to use the key argument in sort(), for example a.sort(key=int). But then an error occurred saying:
ValueError: invalid literal for int() with base 10: '2013-11-20,29,0,0'
Make a key function that returns a tuple of values you want to sort on.
import datetime
a=["2013-11-20,29,0,0","2013-11-20,3,0,2"]
def f(thing):
#separate the values
a,b,c,d = thing.strip().split(',')
# turn one into a datetime.date
y, m, d = map(int, a.split('-'))
a = datetime.date(y, m, d)
# turn the others into ints
b,c,d = map(int, (b,c,d))
# return the values in order of precedence
return (a,b,c,d)
Then use it to sort the list
a.sort(key = f)
Your issue is, that each item in your list is a string. If you sort a string, each character at each position will be compared with eachother. In your example all characters are the same until after the first comma. After the comma, the next characters are a '2' and a '3'. As '3'>'2', the sorting is not as you wish. I assume you want 29 be > 3.
In this particular case, you could just reverse the sorting
a.sort()
a.reverse()
But as you probably have a list with more items, this will not work... The only solution I see is to split each item in your list at the comma ','. Then convert the items which should be considered as integers to int. For example you can do it like this:
a=["2013-11-20,29,0,0","2013-11-20,3,0,2"]
a_temp=[]
for item in a:
splitstr = item.split(',')
i=0
temp = []
for elem in splitstr:
if i>0:
temp_i=int(elem)
else:
temp_i=elem
temp.append(temp_i)
i+=1
a_temp.append(temp)
Your temporary list looks now like this:
[['2013-11-20', 29, 0, 0], ['2013-11-20', 3, 0, 2]]
Then sort it by the position as you wish. This you can do for example like this:
from operator import itemgetter
a_temp_sorted=sorted(a_temp, key=itemgetter(0,1,2,3))
By using the itemgetter you can define in what order you want to sort. Here it is sorted at first by the element 0, then 1, etc... but you can change the order. a_temp_sorted now looks like:
[['2013-11-20', 3, 0, 2], ['2013-11-20', 29, 0, 0]]
Now you can convert your result again to a string. This you can do like this:
a_sorted=[]
for item in a_temp_sorted:
newstring=''
i=0
for elem in item:
if i>0:
temp_i=str(elem)
newstring+=','+temp_i
else:
newstring+=elem
i=1
a_sorted.append(newstring)
a_sorted is now your sorted version of your source a. It now looks like this:
['2013-11-20,3,0,2', '2013-11-20,29,0,0']
i am trying to implement a string comparison algorithm in Python for one of my projects. As i am new to python, i'm learning on the go. But i'm stuck at a step of the algorithm.
At the moment i have list of lists. It is sorted and groupby the length.
mylist = list(list(i[1]) for i in itertools.groupby(sorted(mylist, key=len), len))
>>> [
[['pat'],['cut'],['rat']],
[['sat','pat'],['cut','pat']],
[['rat','cut','pat'],['put','cut','bat'],['mat','gut','lit']]
[[...]]...
]
If we consider mylist[2] elements in a column, it looks like this
mylist[2]
>>> [['rat','cut','pat'],
['put','cut','bat'],
['mat','gut','lit']]
i want to compare each column and return the most frequently occurring element count. i.e at index zero, it is 3(all three are different). For index one it is 2 (since 'cut' appears twice), and in index two, it is 3 again. likewise i need to repeat the process to all the lists of mylist.
It feels im stuck here. Can somebody suggest me a suitable method, perhaps a List Comprehension?
Thank You.
You can use set to extract the unique elements, and zip(*list_of_list) as a trick to "transpose" a list of list. Try this:
lst = [
[['pat'],['cut'],['rat']],
[['sat','pat'],['cut','pat']],
[['rat','cut','pat'],['put','cut','bat'],['mat','gut','lit']]
]
print map(lambda ll: [len(set(l)) for l in zip(*ll)], lst)
Output:
[[3], [2, 1], [3, 2, 3]]
Edit: To get the minimum value of each list, a trivial addition to the above will do:
print map(lambda ll: min([len(set(l)) for l in zip(*ll)]), lst)
Output:
[3, 1, 2]
I'm wondering how to print specific items from a list e.g. given:
li = [1,2,3,4]
I want to print just the 3rd and 4th within a loop and I have been trying to use some kind of for-loop like the following:
for i in range (li(3,4)):
print (li[i])
However I'm Getting all kinds of error such as:
TypeError: list indices must be integers, not tuple.
TypeError: list object is not callable
I've been trying to change () for [] and been shuffling the words around to see if it would work but it hasn't so far.
Using slice notation you can get the sublist of items you want:
>>> li = [1,2,3,4]
>>> li[2:]
[3, 4]
Then just iterate over the sublist:
>>> for item in li[2:]:
... print item
...
3
4
You should do:
for i in [2, 3]:
print(li[i])
By range(n), you are getting [0, 1, 2, ..., n-1]
By range(m, n), you are getting [m, m+1, ..., n-1]
That is why you use range, getting a list of indices.
It is more recommended to use slicing like other fellows showed.
li(3,4) will try to call whatever li is with the arguments 3 and 4. As a list is not callable, this will fail. If you want to iterate over a certain list of indexes, you can just specify it like that:
for i in [2, 3]:
print(li[i])
Note that indexes start at zero, so if you want to get the 3 and 4 you will need to access list indexes 2 and 3.
You can also slice the list and iterate over the lists instead. By doing li[2:4] you get a list containing the third and fourth element (i.e. indexes i with 2 <= i < 4). And then you can use the for loop to iterate over those elements:
for x in li[2:4]:
print(x)
Note that iterating over a list will give you the elements directly but not the indexes.
I am using Python 3.0 to write a program. In this program I deal a lot with lists which I haven't used very much in Python.
I am trying to write several if statements about these lists, and I would like to know how to look at just a specific value in the list. I also would like to be informed of how one would find the placement of a value in the list and input that in an if statement.
Here is some code to better explain that:
count = list.count(1)
if count > 1
(This is where I would like to have it look at where the 1 is that the count is finding)
Thank You!
Check out the documentation on sequence types and list methods.
To look at a specific element in the list you use its index:
>>> x = [4, 2, 1, 0, 1, 2]
>>> x[3]
0
To find the index of a specific value, use list.index():
>>> x.index(1)
2
Some more information about exactly what you are trying to do would be helpful, but it might be helpful to use a list comprehension to get the indices of all elements you are interested in, for example:
>>> [i for i, v in enumerate(x) if v == 1]
[2, 4]
You could then do something like this:
ones = [i for i, v in enumerate(your_list) if v == 1]
if len(ones) > 1:
# each element in ones is an index in your_list where the value is 1
Also, naming a variable list is a bad idea because it conflicts with the built-in list type.
edit: In your example you use your_list.count(1) > 1, this will only be true if there are two or more occurrences of 1 in the list. If you just want to see if 1 is in the list you should use 1 in your_list instead of using list.count().
You can use list.index() to find elements in the list besides the first one, but you would need to take a slice of the list starting from one element after the previous match, for example:
your_list = [4, 2, 1, 0, 1, 2]
i = -1
while True:
try:
i = your_list[i+1:].index(1) + i + 1
print("Found 1 at index", i)
except ValueError:
break
This should give the following output:
Found 1 at index 2
Found 1 at index 4
First off, I would strongly suggest reading through a beginner’s tutorial on lists and other data structures in Python: I would recommend starting with Chapter 3 of Dive Into Python, which goes through the native data structures in a good amount of detail.
To find the position of an item in a list, you have two main options, both using the index method. First off, checking beforehand:
numbers = [2, 3, 17, 1, 42]
if 1 in numbers:
index = numbers.index(1)
# Do something interesting
Your other option is to catch the ValueError thrown by index:
numbers = [2, 3, 17, 1, 42]
try:
index = numbers.index(1)
except ValueError:
# The number isn't here
pass
else:
# Do something interesting
One word of caution: avoid naming your lists list: quite aside from not being very informative, it’ll shadow Python’s native definition of list as a type, and probably cause you some very painful headaches later on.
You can find out in which index is the element like this:
idx = lst.index(1)
And then access the element like this:
e = lst[idx]
If what you want is the next element:
n = lst[idx+1]
Now, you have to be careful - what happens if the element is not in the list? a way to handle that case would be:
try:
idx = lst.index(1)
n = lst[idx+1]
except ValueError:
# do something if the element is not in the list
pass
list.index(x)
Return the index in the list of the first item whose value is x. It is an error if there is no such item.
--
In the docs you can find some more useful functions on lists: http://docs.python.org/tutorial/datastructures.html#more-on-lists
--
Added suggestion after your comment: Perhaps this is more helpful:
for idx, value in enumerate(your_list):
# `idx` will contain the index of the item and `value` will contain the value at index `idx`