Python Removing Specific Strings From List Leaves Them Left Over? - python

I'm writing some code, and I want to search through this list and remove all the 1s at the beginning. Once it hits a 0 I want it to stop and that be the new list. Whenever I have 13 total characters it does what I want - converted = ("1111111011110") but when I have the full 16, converted = ("1111111111011110") it leaves an extra two ones at the beginning.....
Here's my code:
converted = ("1111111111011110")
finalL = []
i = 0
for x in converted:
finalL.append(x)
print(finalL)
for x in finalL:
if finalL[0] == "1":
finalL.remove("1")
print(finalL)
right now it prints the first list:
['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '0']
but then this list: ['1', '1', '0', '1', '1', '1', '1', '0']
I want the second print to print ['0', '1', '1', '1', '1', '0']

If you only have onces and zeros, and you only care for the string from the first zero and beyond, I would do something like the following.
string = '1111111110111111110'
first_zero = string.find('0')
new_string = string[first_zero:] #'0111111110'
Note that this will not work for strings with only ones because find will return -1, which will be the last character of your string. So you would need to make sure that every time a -1 is returned your string is nothing actually.
Or by following your example with loops:
converted = '1111111110111111110'
finalL = ''
for i,elem in enumerate(converted):
if elem=='0':
# if a zero is found, copy the whole string from
# this position
finalL = converted[i:]
break

Related

Increasing order Python

This code makes a connection to hbase, and then prints the result of a given row. But the result is printed like this:
import happybase
connection = happybase.Connection('MacBook-Air.local')
table = connection.table('twitter_db')
row = table.row('2018-09-21 11:55:24')
print(row)
But the result is printed like this:
{'Hashtag:#AFDs': '1', 'Hashtag:#Job': '1', 'Hashtag:#pumpkinpoundcake': '1', 'Lang:und': '81', 'Lang:pt ': '17', 'Hashtag:#InsomniaInFourWords': '2', 'Hashtag:#thegreatindianbooktour': '1', 'Hashtag:#pdx911': '2', 'Hashtag:#US': '1', 'Lang:en ': '246', 'Lang:es ': '31', 'Hashtag:#travelling': '1', 'Hashtag:#prohibition': '1', 'Hashtag:#FF': '2', 'Lang:in ': '15'}
I would like to print on one side all the hashtags with their relative numbers in ascending order and by one or all the languages with their relative numbers in ascending order. For example:
'Hashtag:#FF': '2'
'Hashtag:#AFDs': '1'
'Hashtag:#Job': '1'
.........
----------------
'Lang:en ': '246'
'Lang:und': '81'
'Lang:es ': '31'
.......
For example I could create a method but how?

How to pair 2 list into 1 list

I have a code like this:
def datauji(self):
uji = []
for x in self.fiturs:
a = [x[0],x[-5:]] #I think the problem in this line
uji.append(a)
return uji
with open('DataUjiBaru.csv','wb') as dub:
testing = csv.writer(dub)
datatest = d.datauji()
datatest.pop(0)
for x in datatest:
testing.writerow(x)
I want to pair the value in self.fiturs, In self.fiturs:
F37,0,1,0,1,1,1,0,1,0,2,1,0,0,0,1
F10,8,4,3,3,3,6,8,5,8,4,8,4,5,6,4
F8,1,0,2,0,0,0,2,0,0,0,0,0,2,0,0
So i want to pair index[0] and index[-5:] and write it to the csv, and the output on the csv like this:
F37,"['1', '0', '0', '0', '1']"
F10,"['8', '4', '5', '6', '4']"
F8,"['0', '0', '2', '0', '0']"
My Expectation in that csv is like this:
F37,1,0,0,0,1
F10,8,4,5,6,4
F8,0,0,2,0,0
How can I fix that?
You were correct about the issue with your code, it is found in the line:
a = [x[0],x[-5:]]
This creates nested items that look like this:
['F37', ['1', '0', '0', '0', '1']]
Here are two ways to fix this:
Option 1 - Use the splat* operator:
a = [x[0],*x[-5:]]
Option 2 - Concatenate two slices of your list:
a = x[:1] + x[-5:]
Both of these will remove the nesting of your lists, and instead give you lines looking like:
['F37', '1', '0', '0', '0', '1']
Which you can then write to your output file.

Python, not able to get the index working in my list

I have a list that contains some values as given below:
PC1=list();
PC1=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4]
Thats ok. Now, I do have a string that I enter an "bitsequence" (well, its a sequence of characters 1 and 0...) to:
print ("The main key entered is: " + KEY)
#test key that I enter: 0001001100110100010101110111100110011011101111001101111111110001
Yepp, thats the first step in DES when initial preparing for creating the 16 subkeys I tries to achieve here. So when using the items in the PC1 list I thought that the corresponding character from my KEY string should be picked, I iterate according to:
KEY_PERM = list();
i=0
for i in range(0,56):
print ("index", i, "PC1 ", PC1[i], "value from KEY ", KEY[PC1[i]])
KEY_PERM.insert(i, KEY[PC1[i]])
mm, by this the KEY_PERM list that is now populated based upon the PC1 index should be: 11110000110011001010101011110101010101100110011110001111
but.... it is not, it gives me the list:
['1', '1', '0', '0', '1', '1', '0', '0', '1', '0', '1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '0', '1', '1', '1', '0', '1', '0', '1', '0', '1', '0', '1', '0', '1', '0', '1', '1', '0', '0', '1', '1', '0', '1', '0', '0', '0']
And that is incorrect, for instance, the character in place 41 and 33 in the KEY string is not 0....but 1!
11110000110011001010101011110101010101100110011110001111 and not, as now, 0 and 0 as returned characters.
Please help me out! Yepp, I am a total beginner in Python, but wants to learn. I guess that the initial zeroes in the string might be treated wrong? or that the index runs crazy due to me not looping correctly, or something else... like wrong types etc. I dont now.
I think you got confused what position 33 means. When not in the context of programming, then you would look at the 33rd entry in your list, which in your case is 1.
In Python and many other languages arrays and lists are indexed, starting at 0. So the 1st entry in your list has index 0. So when you tell python key[33] it actually looks up the 34th entry in your list. That is 0 as the script also outputs. What you want is the 33rd entry in the list. Which has index 33-1=32. So you need to do:
for i in range(0,56):
print ("index", i, "PC1 ", PC1[i], "value from KEY ", KEY[PC1[i]-1])
KEY_PERM.insert(i, KEY[PC1[i]-1])
print(''.join(KEY_PERM))
>>> '11110000110011001010101011110101010101100110011110001111'
Notice PC1[i]-1 when using the entry from PC1[i] to acces KEY
Complete Test Script:
PC1=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4]
KEY='0001001100110100010101110111100110011011101111001101111111110001'
KEY_PERM=[]
for i in range(0,56):
KEY_PERM.insert(i, KEY[PC1[i]-1])
print(''.join(KEY_PERM))
prints: 11110000110011001010101011110101010101100110011110001111

Summing numbers in a list in Python with a specific condition

I need to sum linearly the numbers in this list, BUT, only if the next int type number is different from the before:
['2', '4.384508781', '2', '1.38586366', '2', '25.4309252', '1', '9.969634146', '1', '10.3821918', '2', '70.02500521', '1', '12.21172958', '1', '13.53189471', '1']
For example, for the first I want to add 2+4.384508781.
But, in the second time, I want to add only the 1.38586366 to the already (2+4.384508781) since the int is the same as before. And, if it is not, to add the int.
EDIT1:
I simplifed it. I divided the numbers in 2 lists, like this:
['2', '2', '2', '1', '1', '2', '1', '1', '1', '1]
['4.384508781', '1.38586366', '25.4309252', '9.969634146', '10.3821918', '70.02500521', '12.21172958', '13.53189471', '6.166945117', '16.28642897']
What I want to do is, on the first iteration, sum the first 2 and 4.384508781.
But, in the second, since the second number in the first list is the same as before ( 2 = 2 ) I want do add only the 1.38586366. This is put on a mathematic formula, but I just want to know how can I put a condition so that it doesn't sum the INT number in the first list if it is the same as the one previous.
Here's a basic, naive, FORTRAN like solution with your first data type:
int_and_floats = ['2', '4.384508781', '2', '1.38586366', '2', '25.4309252', '1', '9.969634146', '1', '10.3821918', '2', '70.02500521', '1', '12.21172958', '1', '13.53189471', '1', '6.166945117', '1', '16.28642897']
last_int = None
n = len(int_and_floats)
total = 0
for i in range(0, n, 2):
a, b = int(int_and_floats[i]), float(int_and_floats[i + 1])
total += b
if a != last_int:
total += a
last_int = a
print(total)
# 175.775127174
With your second data format, you could just use groupby to chunk the ints together before summing them:
from itertools import groupby
ints = ['2', '2', '2', '1', '1', '2', '1', '1', '1', '1']
floats = ['4.384508781', '1.38586366', '25.4309252', '9.969634146', '10.3821918',
'70.02500521', '12.21172958', '13.53189471', '6.166945117', '16.28642897']
print(sum(map(float, floats)) + sum(int(i) for i, _ in groupby(ints)))
And with numbers instead of strings, your code could be:
from itertools import groupby
ints = [2, 2, 2, 1, 1, 2, 1, 1, 1, 1]
floats = [4.384508781, 1.38586366, 25.4309252, 9.969634146, 10.3821918, 70.02500521, 12.21172958, 13.53189471, 6.166945117, 16.28642897]
print(sum(floats) + sum(i for i, _ in groupby(ints)))
# 175.775127174
a = ['2', '4.384508781', '2', '1.38586366', '2', '25.4309252', '1',
'9.969634146', '1', '10.3821918', '2', '70.02500521', '1',
'12.21172958', '1', '13.53189471', '1']
prev = 0
sm = 0
for each in a:
if each.isdigit() and int(each)!=prev:
sm += int(each)
prev = int(each)
elif '.' in each:
sm += float(each)
print(sm)
should do the trick
Consider such solution for your first list:
ls = ['2', '25.1','2', '25.2','2','25.3']
class Counter():count = 1
def summer(x,y):
if Counter.count>1:
one_before= ls[Counter.count-2]
if y == one_before:
Counter.count+=1
return float(x)
Counter.count+=1
return float(x)+float(y)
summ = reduce(summer,ls)
print summ
it gives the sum of 77.6 which is 2+25.1+(skip)+25.2+(skip)+25.3

Store list contents as two different lists with same indices

so I'm trying to store a list of contents within two different matrices depending on where I'm reading the code from. In other words, I'm going to be reading in a list with this pattern:
['1', '1', '-1'], ['1', '1', '-1'], ['1', '1', '-1'], [], ['1', '1', '-1'], [],
['1', '2', '-1'], ['1', '2', '-1'], ['1', '2', '-1'], [], ['1', '2', '-1'], [], etc
and what I want to do is read and store everything before the first space in a 2D array such as:
inputs[i] = ['1', '1', '-1', '1', '1', '-1', '1', '1', '-1']
inputs[i+1] = ['1', '2', '-1', '1', '2', '-1', '1', '2', '-1']
Then the next set of numbers after the space as:
outputs[i] = ['1', '1', '-1']
outputs[i+1] = ['1', '2', '-1']
While repeating with an increment of i+1 after I've stored the corresponding outputs.
I don't necessarily want to hard code everything because the number of inputs could be different (ie I could have 4 lists of inputs before you get to the space before the outputs). I've tried doing a for loop like:
l = ['1', '1', '-1'], ['1', '1', '-1'], ['1', '1', '-1'], [], ['1', '1', '-1'], [],
['1', '1', '-1'], ['1', '1', '-1'], ['1', '1', '-1'], [], ['1', '1', '-1'], [], etc
for line in l:
if line != []:
inputs[i].append(line)
else:
outputs[i].append(line.next) # Get that output line
line.next() # To skip the following blank line
The problem I have is that I'm not sure where to increment i, and that depending on where i gets incremented, the outputs and inputs won't be on the same index. What would be the best way to store something like this?
If I understand it correctly, the list you want to process contains this kind of sequence:
inputs empty output empty inputs empty output empty inputs empty output empty inputs empty output empty ...
That is, multiple sets of inputs and outputs, delimited by empty lists.
As you iterate over the items in the incoming list.
You could use a flag variable to track whether you're in the middle of processing inputs or outputs, for example like this:
inputs = [[]]
outputs = []
input_mode = True
for lst in lists:
if not lst:
if not input_mode:
inputs.append([])
# flip the mode
input_mode = not input_mode
elif input_mode:
# extend last input list
inputs[-1].extend(lst)
else:
outputs.append(lst)
For example given:
lists = ['1', '1', '-1'], ['1', '1', '-1'], ['1', '1', '-3'], [], ['1', '1', '-4'], [], ['1', '1', '-1'], ['1', '1', '-1'], ['1', '1', '-7'], [], ['1', '1', '-8']
The above implementation will produce inputs and outputs as:
[['1', '1', '-1', '1', '1', '-1', '1', '1', '-3'], ['1', '1', '-1', '1', '1', '-1', '1', '1', '-7']]
[['1', '1', '-4'], ['1', '1', '-8']]
I'm thinking about you want to do.
First of all, if the variable i depends content of lines (you don't predict where is incremented), best way may be do a list:
input = []
output = []
And if you want to store a new value in them use append function:
input.append(aux)
on aux:
isInput = True
aux = []
for line in l:
if line != []:
if isInput:
inputs.append([aux])
isInput = False
else:
outputs.append([aux])
isInput = True
aux = []
else:
aux.append(line.next) # Get that output line
line.next() # To skip the following blank line

Categories

Resources