A comma seperated list of numbers in Python - python

I want to print out from 1 to 1320 like d1,d2,d3,d4 and so on
The command >>> list(range(1320)) will print out like 1,2, 3 etc. so I tried with d(list(range(1320))) but it says NameError: name 'd' is not defined
So my question id how to print the numbers like d1,d2,d3 .....
Maybe I am missing very basic syntax here. Any help?

list(range(1320)) builds a list out of that range of numbers, and when that list is shown in your Python session, it lists the elements separated by commas. [0, 1, 2, ...]
If you want to build a list of d0, d1, d2 etc. you can use a list comprehension.
>>> ['d%s'%i for i in range(1320)]
['d0', 'd1', 'd2', 'd3', ....
But if you actually want to just print those strings separated by commas, you can use join:
>>>> print(', '.join(['d%s'%i for i in range(1320)]))
d0, d1, d2, d3, ...

You can use list comprehension like this:
['d{}'.format(i) for i in range(1320)]
of for Python3.6 and higher:
[f'd{i}' for i in range(1320)]

>>>>['d'+str(i) for i in range(1320)]
This is another way to do the same in one line using basic list comprehension.
Just loop till 1230 and concatenate with 'd'.

Related

How to do `for line.split() in line:` as list comprehension

I'm trying to use python comprehension.
I have a list which is in the format:
name_a:surname_a
name_b:surname_b
name_c:surname_c
My code initially to split each pair in a line into its own variable was:
for lined in self.account:
a, b = line.split(':')
I tried to use this comprehension, but it didn't seem to work:
(a,b) = [line.split(':') for line in self.account]
As mentioned by #MattDMo the colons are missing in your list comprehension. If you add them, a additional problem will appear. If you print the list returned from the list comprehension, it will probably look like this:
[['name_a', 'surname_a\n'], ['name_b', 'surname_b\n'], ['name_c', 'surname_c\n']]
The problem is, that you can't assign it to two variables, because the list contains the same number of elements as lines in the file.
To get the desired result, you have to transpose the two dimensional list, for example by using zip and unpacking ('*'):
>>> with open('test_file.txt') as f:
... (a, b) = zip(*[line.split(':') for line in f])
...
>>> a
('name_a', 'name_b', 'name_c')
>>> b
('surname_a\n', 'surname_b\n', 'surname_c\n')

Python itertools' permutations() usage for several arrays

I'm constructing dictionaries lists in Python, with aim to iterate through each one individually and concatenate all different combinations. There are three different components to each "product" in a dictionary list:
1) a letter, e.g. 'A' (first part of the product code, unique to each product entry). Let's say the range here is:
['A', 'B', 'C']
2) a letter and number, e.g. 'S2' (2nd part, has several variations...might be 'D3' or 'E5' instead)
3) a period ('.') and a letter, e.g. '.X' (3rd part, unique to each product entry). Let's say the range here is:
['.X', '.Y', '.Z']
Since the 2nd part listed above has the most variations, my starting assumption is to construct dicts lists with the 1st and 3rd parts together, in order to reduce the number of different listsdicts, since they are uniquely paired, e.g. 'A.Z'...but, I would still need to split each entry then insert the 2nd part, between them, via some 'concatenate' command. So, question is: if I have another dict list with all variations of the 2nd part, what function(s) should I use to construct all variants of a product?
The total combination of examples:
ListOne = ['A', 'B', 'C']
ListTwo = ['D3', 'D4', 'D5', 'E3', 'E4', 'E5']
ListThr = ['.X', '.Y', '.Z']
I need to create new dicts lists as concatenations of all three dicts lists, e.g. 'AD3.X', but there are no variants for ListOne vs ListThr, it will always be 'A' matched to '.X' or 'B' and 'C' matched to '.Y'...ListTwo products concatenated between ListOne and ListThr products will need to be iterated so all possible combinations are output as a new dict list e.g.
ListOneNew = ['AD3.X', 'AD4.X', AD5.X', 'AE3.X', 'AE4.X', 'AE5.X']
ListTwoNew = ['BD3.Y', 'BD4.Y', 'BD5.Y', <and so on...>]
For simplicity's sake, should the script have a merged version of ListOne and ListThr e.g.
List = ['A.X', 'B.X', 'C.Z']
and then split & concatenate with ListTwo products, or just have three Lists and concatenate from there?
from itertools import product
result = [a[0] + a[1] + a[2] for a in list(product(DictOne, DictTwo, DictThr))]
With list comprehension
final = sorted([a+b+c for c in DictThr for b in DictTwo for a in DictOne])

Python 3.4 Operations on lists or tuples in test files

My problem to solve is:
Open a .txt file, which contains pairs of integers in any form, IE
2,4
10,24
or
(2,4)
(10,24)
or
[(2,4),(10,24)]
The assignment is to caluculate the product of all pairs and add them together. So for the test list that would be (2*4)+(10*24).
I don't really know where to start, what is the most efficient way to put the pairs in the text file? Separated by space, commas, put it as nested lists?
I have tried zipping, creating lists, etc.
with open("txtfile.txt","r") as f:
for line in f:
(list(line.split()))
returns
['2,4']
['10,24']
which is one of the more organized results without very excessive '' notations.
How do I get the elements inside the list to be represented as separate integers instead of a string? How would I then go from there? Is a loop something that can solve the problem?
This is homework.
You dont need use list ,First you need to split your lines with , then use map and int function to get a int list for each digit and use sum function to add the multiple of items , also in this case i use operator.mul:
from operator import mul
with open("txtfile.txt","r") as f :
print sum(mul(*map(int,line.split(','))) for line in f)
248
txtfile.txt :
2,4
10,24
No error checking, quite brute force but it works, as in "when I tried, I got the right output..."
>>> a = '''2,4
10,24
(2,4)
(10,24)
[(2,4),(10,24)]'''
>>> for l in a.split('\n'):
... el = [int(e.strip('[]()')) for e in l.split(',')]
... print sum([i*j for i,j in zip(el[::2],el[1::2])])
8
240
8
240
248
>>>
How does it work?
the element list el is prepared in the 2nd line, first I split on commas every line of (simulated) input, then I stripped out all that unprofitable syntax and turned the result into integers
in the next line of code, for each line of input I pack together in couples (using the builtin zip) the odd and the even elements of the current list of integers, I unpack the couples into variables i and j, take their product and this sequence of products is feed into the builtin sum function, whose result I eventually print.
The unavoidable one-liner
>>> [sum(j*k for j,k in zip(i[::2],i[1::2])) for i in [[int(e.strip('[]()')) for e in l] for l in [l.split(',') for l in a.split('\n')]]]
[8, 240, 8, 240, 248]
>>>
much complication is due to the necessity of keeping lines apart.

How do I make a list a key value in a dictionary?

I need to make a dictionary where you can reference [[1,2],[3,4]] --> ([1,2]:0, [2,3]:0)
I've tried different ways but I can't use a list in a dictionary. So i tried using tuples, but its still the same. Any help is appreciated!
You need to use tuples:
dict.fromkeys((tuple(i) for i in [[1,2],[3,4]]), 0)
or (for python2.7+)
{tuple(i): 0 for i in [[1,2], [3,4]]}
Edit:
Reading the comments, OP probably want to count occurrences of a list:
>>> collections.Counter(tuple(i) for i in [[1,2], [1,2], [3,4]])
Counter({(1, 2): 2, (3, 4): 1})
Lists can't be used as dictionary keys since they aren't hashable (probably because they can be mutated so coming up with a reasonable hash function is impossible). tuple however poses no problem:
d = {(1,2):0, (3,4):0}
Note that in your example, you seem to imply that you're trying to build a dictionary like this:
((1,2):0, (3,4):0)
That won't work. You need curly brackets to make a dictionary.
([1,2]:0, [2,3]:0) is not a dictionary. I think you meant to use: {(1,2):0, (2,3):1}

Trying to create a look-up table but one array has an apostrophe in front

I'm trying to create a look-up table between two arrays which I've created from a text file.
One is letters, LET = '[AS, DF, EG, ET, AS]'
The other is numbers, NUM = [1,3,1,0,6]
I want to be able to retrieve the number corresponding with the pair of letters.
How can I do this?
I think my problem has something to do with the fact that the LET array is a string as indicated by the " ' ". Is there any way I can change this and then tuple the two lists?
'[AS, DF, EG, ET, AS]' is a string. You need to fix your code so it is a list of strings as imm suggests.
Now you can use zip() with the two lists to make a dictionary
>>> LET = ['AS','DF','EG','ET','AS']
>>> NUM = [1,3,1,0,6]
>>> dict(zip(LET, NUM))
{'DF': 3, 'ET': 0, 'AS': 6, 'EG': 1}
note that there is only one of the values for 'AS' in the dictionary since you can't have duplicate keys

Categories

Resources