In short i want to number chars in order from 1 to n without changing the position of the chars in a list.
Suppose I have a list called key = ['c', 'a', 't'] How would i go about
assigning a number to each letter depending on where it is situated in the alphabet with respect to the other letters. Starting at 1 and going until len(key) such that our key becomes [ 2, 1, 3]
I'm really stumped. I have a way to convert them to numbers but very unsure as to how to compare them such that the above happens any help, tips, ideas or explanations would be appreciated.
this is what i have so far...
import string
key = list(input("enter key: ").upper())
num = []
for i in key:
num.append(string.ascii_uppercase.index(i)+1)
This solution assumes that duplicate entries should be assigned the same number, so that
# ['c','a','t'] -> [2, 1, 3]
# ['c','a','t','c','a','t'] -> [2, 1, 3, 2, 1, 3]
You can write a simple function like this:
def get_alphabet_pos(lst):
uniques = sorted(set(lst)) # set() to filter uniques, then order by value
numbers = {letter: i+1 for i, letter in enumerate(uniques)} # build a lookup dict
return [numbers[key] for key in lst]
get_alphabet_pos('cat') # [2, 1, 3]
So here's what happens in the function:
In line 1 of the function we convert your list to a set to remove any duplicate values. From the docs # https://docs.python.org/3/tutorial/datastructures.html#sets:
A set is an unordered collection with no duplicate elements.
Still in line 1 we sort the set and convert it back into a list. Thanks to #StefanPochmann for pointing out that sorted() takes care of the list conversion.
In line 2, we use enumerate() so we can iterate over the indices and values of our list of unique values: https://docs.python.org/3/library/functions.html#enumerate
The rest of line 2 is a simple dict comprehension to build a dictionary of letter -> number mappings. We use the dictionary in line 3 to look up the numbers for each letter in our input dict.
You might have to modify this slightly depending on how you want to handle duplicates :)
I have written the below code:
import itertools
for each in list(itertools.product(list1,list2)):
print each,
It works fine, but I want to learn how to write to print each tuple of this cartesian product list in the same line separated by a space using list comprehension.
Ouput should be something like:
(1, 3) (1, 4) (2, 3) (2, 4)
is list1 = [1,2] & list2 = [3,4]
I tried but syntax error comes. Please help, thanks in advance.
This seems to be what you want (in Python3, for Python2, just remove the parentheses and put a space after print):
print(str([ each for each in list(itertools.product(list1,list2)) ])[1:-1].replace(", (", " ("))
Hope that helps! I really don't know why you would want to do that though. Also, note that with this solution you end up with a string and not a list even though the output is the one specified.
Use the following code(in python 3):
from itertools import product
a = "1 2"
b = "3 4"
A = map(int, (a.split(' ')))
B = map(int, (b.split(' ')))
print(' '.join(map(str, product(A, B))))
I have a list of numbers and I want to extract N elements as lists, and store them in another list.
Example:
list1 = [1,2,3,4,5,6,7,8,9]
resultList = [[1,2,3],[4,5,6],[7,8,9]]
I've done the following
def getLines(square, N):
i = 0
line = [None]*N
lines = list()
for elt in square:
line[i] = elt
i += 1
if i == N:
lines.append(line)
i = 0
return lines
Why do I always get the last list three times
[[7,8,9],[7,8,9],[7,8,9]]
when I call the function getLines(list1, 3).
I also tried to eliminate the temporary list and add the elements directly to resultList like this:
def getLines(square, N):
i = 0
j = 0
lines = [[None]*N]*N # Need to be initialized to be able to index it.
for elt in square:
lines[i][j] = elt
j += 1
if j == N:
i += 1
j = 0
return lines
The last group is still appearing N times. Any hints on how to fix that?
This is because you are creating only one inner list object, and altering it.
In pseudocode, what you are doing is:
Create a list called line assigning [None, None, None] to it
Create an empty list called lines
For three times:
-- Pick n items from the square list
-- Assign these three items to line[0], line[1] and line[2]
-- Append line to lines
So, what you are doing is assigning to individual items of line. This is important - you're not making a new object each time, you're changing individual items in the line list.
At the end of it all, line will point to the list [7, 8, 9]. And you can see lines as being substantially [line, line, line] (a list of three times the same object), so specifically now it will point to [[7,8,9], [7,8,9], [7,8,9]].
To solve this, possibly the solution that most keeps your original code is to re-define line after appending it. This way, the variable name line will refer to a different list each time, and you won't have this problem.
def getLines(square, N):
i = 0
line = [None]*N
lines = list()
for elt in square:
line[i] = elt
i += 1
if i == N:
lines.append(line)
line = [None]*N # Now `line` points to a different object
i = 0
return lines
Of course, there is leaner, more Pythonic code that can do the same thing (I see that an answer has already been given).
EDIT - Ok, here goes a somehow more detailed explanation.
Perhaps one of the key concepts is that lists are not containers of other objects; they merely hold references to other objects.
Another key concept is that when you change an item in a list (item assignment), you're not making the whole list object become another object. You're merely changing a reference inside it. This is something we give for granted in a lot of situations, but somehow becomes counter-intuitive when we'd want things to go the other way and "recycle" a list.
As I was writing in the comments, if list was a cat named Fluffy, every time you're appending you're creating a mirror that points to Fluffy. So you can dress Fluffy with a party hat, put a mirror pointing to it, then give Fluffy a clown nose, put on another mirror, then dress Fluffy as a ballerina, add a third mirror, and when you look at the mirrors, all three of them will show the ballerina Fluffy. (Sorry Fluffy).
What I mean is that in practice in your first script, when you do the append:
lines.append(line)
by the first concept I mentioned, you are not making lines contain the current status of line as a separate object. You are appending a reference to the line list.
And when you do,
line[i] = elt
by the second concept, of course line is always the same object; you're just changing what's referenced at the i-th position.
This is why, at the end of your script, lines will appear to "contain three identical objects": because you actually appended three references to the same object. And when you ask to see the content of lists, you will read, three times, the list object in its current status.
In the code I provided above, I re-define the name lists to make it reference a brand new list every time it's been appended to lists:
lines.append(line)
line = [None]*N # Now `line` points to a different object
This way, at the end of the script I have "three different cats" appended, and each one was conveniently named Fluffy just until I had appended it, to give room for a new Fluffy list after that.
Now, in your second script, you do something similar. The key instruction is:
lines = [[None]*N]*N # Need to be initialized to be able to index it.
In this line, you are creating two objects:
- the list [None, None, None]
- the list named lines, which contains N references to the same list [None, None, None].
What you did was just to create straight away Fluffy and the three mirrors pointing at him.
In fact if you change lines[0][2], or lines[1][2], you're just changing the same item [2] of your same Fluffy.
What you actually wanted to do is,
lines = [[None]*N for i in range(N)]
which creates three different cats - I mean, lists, and have lines point to the three.
You might consider solving this like:
def getLines(square, N):
return [square[i:i + N] for i in range(0, len(square), N)]
For example: getLines([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) will return [[1, 2, 3], [4, 5, 6], [7, 8, 9]], or getLines([1, 2, 3, 4, 5, 6, 7, 8, 9], 2) results in [[1, 2], [3, 4], [5, 6], [7, 8], [9]], and so on.
Intro
I'm trying to do something that sounds simple, but so far I'm not having luck finding the answer. I have 2 lists in a redis 2.6.4 standalone server(no cluster):
list1 = [4, 5 ,6]
list2 = [1, 2, 3]
The problem
And I need to concatenate the lists to produce something like this:
list3 = list1 + list2
list3 = [4, 5, 6, 1, 2, 3] <- I need to preserve order, list1 and then list 2
list4 = list2 + list1
list4 = [1, 2, 3, 4, 5, 6]
The question
Since redis use linked lists to store this lists I was expecting to have a straightforward way of doing this, does such a way exists? what's the usual way of doing this in redis?
Thanks in advance!
The easiest way to do this safely is to use LUA scripting, this way you have the guarantee that the resulting list is not missing any element (and you can easily preserve the order).
If LUA is not an option then you need to do this client side and use watch those keys for changes (see transaction in redis and WATCH command)
Here is the Redis command using Lua:
eval "for i,l in ipairs(ARGV) do for i,v in ipairs(redis.call('lrange',l,0,-1)) do redis.call('rpush',KEYS[1],v) end end" 1 list3 list1 list2
As an added bonus you can specify any number of lists to append into your master list by simply adding more list keys at the end
I have the following question for homework
Define a function append lists that
takes a list of lists and returns a
new list containing the sublist
values. For example, append lists([[1,
2], [3, 4], [5]]) should return the
list [1, 2, 3, 4, 5] and append
lists([[1, 2], [3], [[4, 5]]]) should
return the list [1, 2, 3, [4, 5]].
I've tried various ways of creating this function in order to append the list so it gives the desired output to no avail so I came here looking for some help. I've found a few other ways of going about this online, but they use extensive methods that we haven't even dabbled in as of yet in my CPSC 121 class. We're limited to the basics in what we've learned.
Any help would be much appreciated!
By now, it is likely that the assignment is gone, but here is a solution:
def append_lists(lists):
output = []
for l in lists:
for e in l:
output.append(e)
return output
This appends each element of each list to the output of the function, which eliminates exactly one level of nesting in the elements.