How to pair 2 list into 1 list - python

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.

Related

Python Removing Specific Strings From List Leaves Them Left Over?

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

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?

Python: Combine triple into a single string [duplicate]

This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Apply function to each element of a list
(4 answers)
Closed 6 months ago.
How to join every sublist to a single string in Python?
Here is the list :
L=[['1', '1', '0', '0', '0'],['1', '1', '1', '1', '0'],['0', '0', '1', '1', '0']]
My desired list would be :
D=['11000','11110','00110']
L = [['1', '1', '0', '0', '0'],['1', '1', '1', '1', '0'],['0', '0', '1', '1', '0']]
D = [''.join(sub_list) for sub_list in L]
You can either use a list comprehension:
L = [
['1', '1', '0', '0', '0'],
['1', '1', '1', '1', '0'],
['0', '0', '1', '1', '0']
]
D = [''.join(l) for l in L]
or the map function:
D = map(''.join, L) # returns a generator in python3, cast it to list to get one
Note that the most pythonic way of doing this is the list comprehension.
flat list can be made through reduce easily.
All you need to use initializer - third argument in the reduce function.
reduce(
lambda result, _list: result.append(''.join(_list)) or result,
L,
[])
or map and reduce in combination,
import operator
map(lambda l: reduce(operator.iconcat, l), L)
Above code works for both python2 and python3, but you need to import reduce module as from functools import reduce. Refer below link for details.
for python2
for python3

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

Value Error in python numpy

I am trying to remove rows with ['tempn', '0', '0'] in it. Rows with ['tempn', '0'] should not be removed however.
my_input = array([['temp1', '0', '32k'],
['temp2', '13C', '0'],
['temp3', '0', '465R'],
['temp4', '0', '0'],
['temp5', '22F', '0'],
['temp6', '0', '-15C'],
['temp7', '0', '0'],
['temp8', '212K', '1'],
['temp9', '32C', '0'],
['temp10', '0', '19F']],
dtype='|S2'), array([['temp1', '15K'],
['temp2', '0'],
['temp3', '16C'],
['temp4', '0'],
['temp5', '22F'],
['temp6', '0'],
['temp7', '457R'],
['temp8', '305K'],
['temp9', '0'],
['temp10', '0']], dtype='|S2')]
Based on a previous question, I tried
my_output = []
for c in my_input:
my_output.remove(c[np.all(c[:, 1:] == '1', axis = 1)])
I sprung up with a value error however, saying truth value of an array of more than one element is ambiguous. Thanks!
The trick is to compare the elements individually rather than both at the same time, which is probably why you were getting the error.
final_out = []
for item1 in my_input:
my_output = []
for item2 in item1:
try:
if item2[1] != '0' or item2[2] != '0':
my_output.append(item2)
except IndexError:
my_output.append(item2)
final_out.append(np.array(my_output))
This will preserve your list of array structure while removing ['tempn', '0', '0'].

Categories

Resources