How to add each number to list in python? - python

I have following variable:
number = "456367"
I need to add it to list by one number, like this:
list = [['4', '5', '6', '3', '6', '7']]
How can I achieve this?

Since a string is iterable, pass it to the list constructor:
>>> list("456367")
['4', '5', '6', '3', '6', '7']
Which is why you would not want to name the result list because you would stomp on the name of that convenient function ;-)
If you really want [['4', '5', '6', '3', '6', '7']] vs just a list of characters:
>>> s="456367"
>>> map(list, zip(*s))
[['4', '5', '6', '3', '6', '7']]
Or,
>>> [list(s)]
[['4', '5', '6', '3', '6', '7']]
But I am assuming with the first answer that the extra brackets were a typo.

>>> number = "456367"
>>> [char for char in number]
['4', '5', '6', '3', '6', '7']

Related

Remove an element in Python list with partial word in list

I have a list that looks like this and I've tried the following code and nothing seems to work. My list called "ss" looks like this and I'm trying to remove any elements with "Sheet" in list:
ss = ['14', '13', '11', '10', '9', '8', '6', '3', '2', '1', '0', '7', '4', '12', '5', 'Sheet12', 'Sheet1']
I have tried variations of this and they do nothing:
ssnew = list(filter( lambda s: not (s[0:4]=="Sheet"), ss))
or,
newss = {ss.replace("Sheet","")for x in ss}
I need my new list newss to look like this -->
newss = ['14', '13', '11', '10', '9', '8', '6', '3', '2', '1', '0', '7', '4', '12', '5']
Use a comprehension:
>>> [i for i in ss if not i.startswith('Sheet')]
['14',
'13',
'11',
'10',
'9',
'8',
'6',
'3',
'2',
'1',
'0',
'7',
'4',
'12',
'5']
Since you do mention that list elements should not contain "Sheet" with no other requirement, then this list comprehension is correct:
print([x for x in ss if 'Sheet' not in x])
Another solution would be:
lst = [i for i in ss if i.isdigit()]
print(lst)

How to find all possible combinations from nested list containing list and strings?

I am trying to get all possible pattern from list like:
input_x = ['1', ['2', '2x'], '3', '4', ['5', '5x']]
As we see, it has 2 nested list ['2', '2x'] and ['5', '5x'] here.
That means all possible pattern is 4 (2 case x 2 case), the expect output is:
output1 = ['1','2' , '3', '4', '5']
output2 = ['1','2x', '3', '4', '5']
output3 = ['1','2' , '3', '4', '5x']
output4 = ['1','2x', '3', '4', '5x']
I tried to search how to, but I can not find any examples (because of I have no idea about "keyword" to search)
I think python has inner libraries/methods to handle it.
One way to achieve this is via using itertools.product. But for using that, you need to firstly wrap the single elements within your list to another list.
For example, firstly we need to convert your list:
['1', ['2', '2x'], '3', '4', ['5', '5x']]
to:
[['1'], ['2', '2x'], ['3'], ['4'], ['5', '5x']]
This can be done via below list comprehension as:
formatted_list = [(l if isinstance(l, list) else [l]) for l in my_list]
# Here `formatted_list` is containing the elements in your desired format, i.e.:
# [['1'], ['2', '2x'], ['3'], ['4'], ['5', '5x']]
Now call itertools.product on the unpacked version of the above list:
>>> from itertools import product
# v `*` is used to unpack the `formatted_list` list
>>> list(product(*formatted_list))
[('1', '2', '3', '4', '5'), ('1', '2', '3', '4', '5x'), ('1', '2x', '3', '4', '5'), ('1', '2x', '3', '4', '5x')]
If you don't want to convert your list to all sub list then
You can try something like this :
input_x = ['1', ['2', '2x'], '3', '4', ['5', '5x'],['6','6x']]
import itertools
non_li=[]
li=[]
for i in input_x:
if isinstance(i,list):
li.append(i)
else:
non_li.append(i)
for i in itertools.product(*li):
sub=non_li[:]
sub.extend(i)
print(sorted(sub))
output:
['1', '2', '3', '4', '5', '6']
['1', '2', '3', '4', '5', '6x']
['1', '2', '3', '4', '5x', '6']
['1', '2', '3', '4', '5x', '6x']
['1', '2x', '3', '4', '5', '6']
['1', '2x', '3', '4', '5', '6x']
['1', '2x', '3', '4', '5x', '6']
['1', '2x', '3', '4', '5x', '6x']

Search a list and split

First of all sorry for the very basic question but I haven't been able to find an example with the end results I need. In the following example I have a list with numbers and sometimes the numbers are joined like index 2 and 5 in the following list.
list = ['1', '2', '3, 4', '5', '6', '7, 8', '9', '10']
I would like to search the list and split when it finds a comma so the end result is the following:
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
What would be the easiest way to accomplish this?
>>> [x for y in ['1', '2', '3, 4', '5', '6', '7, 8', '9', '10'] for x in y.split(', ')]
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
An alternative method is:
>>> my_list = ['1', '2', '3, 4', '5', '6', '7, 8', '9', '10']
>>> sum((item.split(', ') for item in my_list), [])
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
or
>>> ', '.join(my_list).split(', ')
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

Printing a variable and appending it with a line from a file in a loop

I've researched this already but I can't find an exact answer. I've found answers for appending when there's 2 lists involved but this is different so here goes.
I'm creating a really basic fuzzer but I'm having issues appending the directory names to the end of the address. Here's what I have so far.
The expected output is as follows;
www.website.com/1
www.website.com/2
www.website.com/3
www.website.com/4
etc. But I'm getting something completely different. Here's the first piece of code I tested.
>>> host = "www.website.com/"
>>> path = [line.strip() for line in open("C:/Users/Public/Documents/tester.txt", 'r')]
>>> print str(host) + str(path)
which returns the following
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
The second attempt was this;
>>> host = "www.website.com/"
>>> path = [line.strip() for line in open("C:/Users/Public/Documents/tester.txt", 'r')]
>>> for line in path:
print str(host) + str(path)
Which returned this;
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
www.website.com/['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
I can see exactly what's happening and why it's happening but I can't figure out how to arrive at the expected output. I'll also need to filter out the special characters which I didn't think 'print' would pick up. Maybe there's different rules for print when it's reading something as a list.
I've thought of stupid complex methods such as counting the lines in the file and then throwing it into a while loop using that count but I'm sure there's something I can use or something I've done wrong. My Python knowledge isn't fantastic.
Can anybody help with this?
You were nearly there , when using the for loop , concatenate the elements from the list (which in your case is in variable 'line') , not the complete list again .
Code -
for line in path:
print str(host) + str(line)

Multiple sorting in Python

I have an array with these datas:
[['1', '7', '14'], ['1', '1', '3'], ['1', '12', '3'], ['2', '3', '1'], ['1', '4', '9']]
I like to sort it (multiple):
>>> sorted(datas,key=lambda x:(x[0], x[1]))
[['1', '1', '3'], ['1', '12', '3'], ['1', '4', '9'], ['1', '7', '14'], ['2', '3', '1']]
but after sorted as it seems the 12 < 4. It should be:
[['1', '1', '3'], ['1', '4', '9'], ['1', '7', '14'], ['1', '12', '3'], ['2', '3', '1']]
Any idea? I need not natural sorting.
There is not wrong with sorted behaviour. Your data are lists of string, so it's doable.
>>> data = ['1', '12', '3', '2']
>>> sorted(data)
['1', '12', '2', '3']
If you want to sort as integer, it must be converted.
>>> sorted(data)
['1', '12', '2', '3']
>>> data = [['1', '7', '14'], ['1', '1', '3'], ['1', '12', '3'], ['2', '3', '1'], ['1', '4', '9']]
>>> sorted(data, key=lambda x: map(int, x))
[['1', '1', '3'], ['1', '4', '9'], ['1', '7', '14'], ['1', '12', '3'], ['2', '3', '1']]
Convert x[1] to int(x[1]):
sorted(d,key=lambda x:(int(x[0]), int(x[1])))
Output:
[['1', '1', '3'], ['1', '4', '9'], ['1', '7', '14'], ['1', '12', '3'], ['2', '3', '1']]
You are comparing strings, not ints. Therefor the order you get is the lexicographical order.
If you convert to int first
sorted(data, key=lambda x:(int(x[0]), int(x[1])))
you will get the desired result
[['1', '1', '3'], ['1', '4', '9'], ['1', '7', '14'], ['1', '12', '3'], ['2', '3', '1']]
Currently your sort is working on tuples string values. String values are determined similarly to any other iterable. When it compares two strings, it goes character by character from left-to-right or index 0 to index n-1 where n is the length of the iterable, until it finds one character that is larger than another. so when comparing '12' and '4', it notices that '4' is greater than '1' so it finishes right there. This system of ordering is known as lexicographical order.
To see the "value" of a character (In Python, a character is just a string of length 1), just use the ord function:
>>> ord('1')
49
>>> ord('4')
52
And to validate that the string '12' is indeed less than '4' because ord('1') < ord('4'):
>>> '12' < '4'
True
If you want to sort by the integer values of the strings, you have to convert the strings to ints by using the built-in int constructor.
sorted(datas,key=lambda x: (int(x[0]), int(x[1]))
Or if you want to cleanly handle iterables of all sizes, simply use a tuple-generator for the key:
sorted(datas,key=lambda x: tuple(int(e) for e in x))

Categories