Jump to content

Python question

Go to solution Solved by Azgoth 2,

Thanks for the tips I appreciate it, I will look into those very soon. I still have the problem of switching it into 8-bit binary. Look I need to turn this...

List1=(0,1,1,0,1,0,0,1,0,0,0,0,1,1,1,1)

Into this....

List2=(01101001,00001111)

But I can't get them to do that what I've tried so far only gives me things like this....

Badlist=((0)(1)(1)(0))

And just giving me back a duplicate list that is the same as what I put in...

So you said they should be represented as strings and not integers?

Oh, my first post had some code that should group the items in list1 by eight and put them in list2.  Just remove the int() part--leave the "".join(...) part, though--and your list2 should look like: ['01101001', '00001111', ...]

 

And yes, binary values should be represented as strings in Python, because it doesn't have a special built-in binary number type.  E.g., if you use the bin() function to convert something to binary, it will return a string: bin(4) returns the literal string "0b100".  You don't strictly need the 0b at the front, but it can't hurt to add it.

 

Here's the loop from my first post, storing binary values as strings:

foo = [1,1,0,0,1,0,1,0]final_digits = []# Store blocks of 8 digits as strings in final_digitsfor i in range(0, len(foo), 8):    temp = "".join(str(j) for j in foo[i:i+8])    final_digits.append(temp)# Or, read the strings as binary numbers, and convert to base 10.for i in range(0, len(foo), 8):    temp = int("".join(str(j) for j in foo[i:i+8]), 2)    final_digits.append(temp)

A bit more in-depth info on what this is doing:

  • range(0, len(foo), 8) creates a range object, which has every eighth number between 0 and len(foo).  So, 0, 8, 16, etc.
  • "".join(...) joins whatever strings of text are between the parentheses, putting whatever is before the .join() between each item.  In this case, it's putting an empty string--""--between each one, so it just concatenates whatever values are inside the parentheses into a single string.
  • str(j) for j in foo[i:i+8] is Python's wonderful list comprehension syntax.  It takes the value i, which is whatever number the for loop is currently using from the range() object (so, every eighth number from 0 to len(foo)), takes a slice of the list foo starting at that number and going forward eight more values, and converts each item into a string.  Then it makes those all into a list.  This is equivalent to
foo = [1, 1, 0, 0, ...]final digits = []for i in range(0, len(foo), 8):    temp1 = foo[i:i+8]    temp2 = ""                 # empty string    for k in temp1:        temp2.append(str(k))
  • int(..., 2) takes the resulting string of ones and zeros, interprets it as a base 2/binary number, and converts it into base 10.

You should use the int(..., 2) bit if you need to do actual math on these values, like multiplying and dividing.  You can leave them as strings (i.e., not use int(..., 2)) if you just need to count how often they appear.

 

Not using int(..., 2) will give you a final_digits list that looks like ['11001100', '00100101', ...], while using int(..., 2) gives a final_digits list that looks like [203, 56, 48, ...].

Ok so I'm new to programing and I've started a project and I'm stuck.I've looked for answers but don't really know the question (per se).ok so up to this point I've got a large list of zeros and ones(example: list1= (0,0,1,0,1,0,0,1,1,1,0,0,1,0,1,0)) ok the list is quite large and what I need is a list of all the digits separated into 8 bits so position 0 to 7 (in the example) would look like this list2=(00101001,11001010, and so on) my list is divisible by 8 so it would even spread. I can't figure out how to accomplish this, again I'm new to this I'm 25 I guess I started kinda late but I'm learning any help would be appreciated thanks.

Link to comment
https://linustechtips.com/topic/497817-python-question/
Share on other sites

Link to post
Share on other sites

probably something with a for loop and list1.length()/8, with a second loop inside that on each iteration of the outside loop puts together 8 of the bits into one value of the second list.

I know how to locate each digit in position (x) where x <= len (list1)-1 x starting at 0 then each iteration x=x+1

I need a way to put them together in a second list, every time I try it always has a space in between or it turns them into sublists I need to turn the first 8 digits into a 8 digit integer, if what I'm saying is confusing plz let me know and I'll try to explain again

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6653542
Share on other sites

Link to post
Share on other sites

I know how to locate each digit in position (x) where x <= len (list1)-1 x starting at 0 then each iteration x=x+1

I need a way to put them together in a second list, every time I try it always has a space in between or it turns them into sublists I need to turn the first 8 digits into a 8 digit integer, if what I'm saying is confusing plz let me know and I'll try to explain again

well, very crude way would be is have the small loop do the following: ("i" is the counter of the for loop)

--

temporaryParameter=0

- for loop starts here -

temporaryParameter = temporaryParameter * 2

if bit i ==1 then temporaryParameter + 1

-for loop ends here-

list2[<counter of big loop>] = temporaryParameter

--

and insert that bit in the bigger loop that runs trough the entire list1

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6653582
Share on other sites

Link to post
Share on other sites

well, very crude way would be is have the small loop do the following: ("i" is the counter of the for loop)

--

temporaryParameter=0

- for loop starts here -

temporaryParameter = temporaryParameter * 2

if bit i ==1 then temporaryParameter + 1

-for loop ends here-

list2[<counter of big loop>] = temporaryParameter

--

and insert that bit in the bigger loop that runs trough the entire list1

Like I said I'm new to this and I didn't understand that at all but thanks for trying to help me out though

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6653612
Share on other sites

Link to post
Share on other sites

Slicing can be used to extract the groups of digits.

full = [0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0]group1 = full[0:8]  # returns index 0 through 7 in a listgroup2 = full[8:16]  # returns index 8 through 15 in a list# group1 contains [0, 0, 1, 1, 0, 0, 1, 1]# group2 contains [1, 1, 0, 0, 1, 1, 0, 0]

This can be modified to work with an array of any size by using a loop and changing the section being sliced.

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6653715
Share on other sites

Link to post
Share on other sites

Slicing can be used to extract the groups of digits.

full = [0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0]group1 = full[0:8]  # returns index 0 through 7 in a listgroup2 = full[8:16]  # returns index 8 through 15 in a list# group1 contains [0, 0, 1, 1, 0, 0, 1, 1]# group2 contains [1, 1, 0, 0, 1, 1, 0, 0]
This can be modified to work with an array of any size by using a loop and changing the section being sliced.

Ok so what I need to happen is say your group 1 needs to show the integer 00110011 and group 2 shows 11001100 as an integer as well

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6654163
Share on other sites

Link to post
Share on other sites

Ok so what I need to happen is say your group 1 needs to show the integer 00110011 and group 2 shows 11001100 as an integer as well

 

You need to be more specific. What exactly are you trying to do?

  • Print "00110011" to the screen?
  • Print "51" to the screen? (ie: convert binary to decimal)
  • Store one of the above values in a variable?
  • Something else?
Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6654377
Share on other sites

Link to post
Share on other sites

To concatenate a list of digits into a single number, you can convert each digit to a string, concatenate the strings, and convert back to a number:

foo = [1,1,0,0,1,0,1,0]bar = int("".join(str(i) for i in foo))

This takes each item in foo and converts it into a string (str(i) for i in foo), joins the resulting strings together, separating them with a blank/empty string ("".join(...)), then converts the final result to an int.  You can then iterate over your list with the digits in your list, using list slices (list[a:b] notation).

foo = [1,1,0,0,1,0,1,0]final_digits = []for i in range(0, len(foo), 8):    temp = int("".join(str(j) for j in foo[i:i+8]))    final_digits.append(temp)

But int() gives a base-10 number, and I suspect you're doing something with binary date, since you're using 1s and 0s and blocks of 8 digits.  What exactly are you using these for?  There are ways to deal with binary/hex/byte data in Python, some of which can be odd (e.g., binary/hex data are stored as literal strings, usually prefaced with '0b' and '0x' respectively, but they don't have to be).  Knowing what you're trying to do could help us give you more specific information/help.

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6654412
Share on other sites

Link to post
Share on other sites

To concatenate a list of digits into a single number, you can convert each digit to a string, concatenate the strings, and convert back to a number:

foo = [1,1,0,0,1,0,1,0]bar = int("".join(str(i) for i in foo))
This takes each item in foo and converts it into a string (str(i) for i in foo), joins the resulting strings together, separating them with a blank/empty string ("".join(...)), then converts the final result to an int. You can then iterate over your list with the digits in your list, using list slices (list[a:b] notation).
foo = [1,1,0,0,1,0,1,0]final_digits = []for i in range(0, len(foo), 8):    temp = int("".join(str(j) for j in foo[i:i+8]))    final_digits.append(temp)
But int() gives a base-10 number, and I suspect you're doing something with binary date, since you're using 1s and 0s and blocks of 8 digits. What exactly are you using these for? There are ways to deal with binary/hex/byte data in Python, some of which can be odd (e.g., binary/hex data are stored as literal strings, usually prefaced with '0b' and '0x' respectively, but they don't have to be). Knowing what you're trying to do could help us give you more specific information/help.

Ok to be more specific I have written a program that has to do with primes semi primes, and powers and I have a few interesting lists that come out of my calculations one of which is a string of binary numbers 1s and 0s. 8 bits or 1 byte is an arbitrary way I am wanting to analyze the list I have handwritten a small portion of the list into a graph of how of a string of 8 in a paticular order has come up and all the samples I've done this way have coincidentally followed zipf's law but since they are of equal length the only way that is possible is for it to be conveying information, I was going to start with ascii and work downwards to simpler and simpler methods of deciphering the binary code so I'd prefer it to be a "string of 8" in a list appending the next 8 as a string and so on (example: list1=(00110011,11001100,00111001, so on and so forth))

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6655678
Share on other sites

Link to post
Share on other sites

<p>

You need to be more specific. What exactly are you trying to do?

  • Print "00110011" to the screen?
  • Print "51" to the screen? (ie: convert binary to decimal)
  • Store one of the above values in a variable?
  • Something else?

Please see my response to Azgoth 2

(I didn't know if you were following so I reply ed like this so you would get notified as well)

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6655724
Share on other sites

Link to post
Share on other sites

Ok to be more specific I have written a program that has to do with primes semi primes, and powers and I have a few interesting lists that come out of my calculations one of which is a string of binary numbers 1s and 0s. 8 bits or 1 byte is an arbitrary way I am wanting to analyze the list I have handwritten a small portion of the list into a graph of how of a string of 8 in a paticular order has come up and all the samples I've done this way have coincidentally followed zipf's law but since they are of equal length the only way that is possible is for it to be conveying information, I was going to start with ascii and work downwards to simpler and simpler methods of deciphering the binary code so I'd prefer it to be a "string of 8" in a list appending the next 8 as a string and so on (example: list1=(00110011,11001100,00111001, so on and so forth))

That actually sounds pretty interesting.  Are you using numpy and matplotlib, by chance?  If you're not, those are both great libraries for doing numerical analysis (numpy) and graphing/plotting/making pretty pictures from data (matplotlib).  And scipy, for more general scientific computing.

 

So if I understand what you're saying correctly, you want to treat your data like it's binary for the sake of doing math with it or plotting it.  You can always convert it into decimal/base-10 for doing math, since binary numbers are stored as strings and you can't do math on them directly.  You can leave them as strings to keep them as purely binary data, though.

 

To cast a string of ones and zeros from binary into a base-10 integer, you can use a second optional argument in int() to specify what base you're converting from:

foo = '11010010'bar = int(foo, 2) # bar now has the decimal value 210, and you can do math with it# Cast bar back into binarybar = bin(bar)# Cast bar into hexadecimalbar = hex(bar)

And depending what exactly you're plotting, the pyplot part of matplotlib has some very nice plotting tools for plotting lines, scatter plots, histograms, etc., so give that a look if you're not using it.

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6659003
Share on other sites

Link to post
Share on other sites

That actually sounds pretty interesting. Are you using numpy and matplotlib, by chance? If you're not, those are both great libraries for doing numerical analysis (numpy) and graphing/plotting/making pretty pictures from data (matplotlib). And scipy, for more general scientific computing.

So if I understand what you're saying correctly, you want to treat your data like it's binary for the sake of doing math with it or plotting it. You can always convert it into decimal/base-10 for doing math, since binary numbers are stored as strings and you can't do math on them directly. You can leave them as strings to keep them as purely binary data, though.

To cast a string of ones and zeros from binary into a base-10 integer, you can use a second optional argument in int() to specify what base you're converting from:

foo = '11010010'bar = int(foo, 2) # bar now has the decimal value 210, and you can do math with it# Cast bar back into binarybar = bin(bar)# Cast bar into hexadecimalbar = hex(bar)
And depending what exactly you're plotting, the pyplot part of matplotlib has some very nice plotting tools for plotting lines, scatter plots, histograms, etc., so give that a look if you're not using it.

Thanks for the tips I appreciate it, I will look into those very soon. I still have the problem of switching it into 8-bit binary. Look I need to turn this...

List1=(0,1,1,0,1,0,0,1,0,0,0,0,1,1,1,1)

Into this....

List2=(01101001,00001111)

But I can't get them to do that what I've tried so far only gives me things like this....

Badlist=((0)(1)(1)(0))

And just giving me back a duplicate list that is the same as what I put in...

So you said they should be represented as strings and not integers?

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6659732
Share on other sites

Link to post
Share on other sites

Thanks for the tips I appreciate it, I will look into those very soon. I still have the problem of switching it into 8-bit binary. Look I need to turn this...

List1=(0,1,1,0,1,0,0,1,0,0,0,0,1,1,1,1)

Into this....

List2=(01101001,00001111)

But I can't get them to do that what I've tried so far only gives me things like this....

Badlist=((0)(1)(1)(0))

And just giving me back a duplicate list that is the same as what I put in...

So you said they should be represented as strings and not integers?

 

011010001 isn't a valid integer. Integers are stored in decimal (base 10) and they don't have leading zeros. Trying to assign an integer with a leading zero will throw an error in Python 3.

>>> i = 011010001  File "<stdin>", line 1    i = 011010001                ^SyntaxError: invalid token

And will give you a result in octal (base 8) in Python 2

>>> i = 011010001>>> i2363393

For reference here's the binary (base 2)

>>> i = 0b011010001>>> i209>>> bin(i)'0b11010001'

You were already shown how to turn a list of integers into a string with join so why not do that? Then append the results to a new list and you'll have this

["011010001", "00001111", etc]

You were also shown how to convert that string to an integer, and from an integer back into a binary string.

 

What else do you need?

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6659900
Share on other sites

Link to post
Share on other sites

Thanks for the tips I appreciate it, I will look into those very soon. I still have the problem of switching it into 8-bit binary. Look I need to turn this...

List1=(0,1,1,0,1,0,0,1,0,0,0,0,1,1,1,1)

Into this....

List2=(01101001,00001111)

But I can't get them to do that what I've tried so far only gives me things like this....

Badlist=((0)(1)(1)(0))

And just giving me back a duplicate list that is the same as what I put in...

So you said they should be represented as strings and not integers?

Oh, my first post had some code that should group the items in list1 by eight and put them in list2.  Just remove the int() part--leave the "".join(...) part, though--and your list2 should look like: ['01101001', '00001111', ...]

 

And yes, binary values should be represented as strings in Python, because it doesn't have a special built-in binary number type.  E.g., if you use the bin() function to convert something to binary, it will return a string: bin(4) returns the literal string "0b100".  You don't strictly need the 0b at the front, but it can't hurt to add it.

 

Here's the loop from my first post, storing binary values as strings:

foo = [1,1,0,0,1,0,1,0]final_digits = []# Store blocks of 8 digits as strings in final_digitsfor i in range(0, len(foo), 8):    temp = "".join(str(j) for j in foo[i:i+8])    final_digits.append(temp)# Or, read the strings as binary numbers, and convert to base 10.for i in range(0, len(foo), 8):    temp = int("".join(str(j) for j in foo[i:i+8]), 2)    final_digits.append(temp)

A bit more in-depth info on what this is doing:

  • range(0, len(foo), 8) creates a range object, which has every eighth number between 0 and len(foo).  So, 0, 8, 16, etc.
  • "".join(...) joins whatever strings of text are between the parentheses, putting whatever is before the .join() between each item.  In this case, it's putting an empty string--""--between each one, so it just concatenates whatever values are inside the parentheses into a single string.
  • str(j) for j in foo[i:i+8] is Python's wonderful list comprehension syntax.  It takes the value i, which is whatever number the for loop is currently using from the range() object (so, every eighth number from 0 to len(foo)), takes a slice of the list foo starting at that number and going forward eight more values, and converts each item into a string.  Then it makes those all into a list.  This is equivalent to
foo = [1, 1, 0, 0, ...]final digits = []for i in range(0, len(foo), 8):    temp1 = foo[i:i+8]    temp2 = ""                 # empty string    for k in temp1:        temp2.append(str(k))
  • int(..., 2) takes the resulting string of ones and zeros, interprets it as a base 2/binary number, and converts it into base 10.

You should use the int(..., 2) bit if you need to do actual math on these values, like multiplying and dividing.  You can leave them as strings (i.e., not use int(..., 2)) if you just need to count how often they appear.

 

Not using int(..., 2) will give you a final_digits list that looks like ['11001100', '00100101', ...], while using int(..., 2) gives a final_digits list that looks like [203, 56, 48, ...].

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6659991
Share on other sites

Link to post
Share on other sites

Oh, my first post had some code that should group the items in list1 by eight and put them in list2. Just remove the int() part--leave the "".join(...) part, though--and your list2 should look like: ['01101001', '00001111', ...]

And yes, binary values should be represented as strings in Python, because it doesn't have a special built-in binary number type. E.g., if you use the bin() function to convert something to binary, it will return a string: bin(4) returns the literal string "0b100". You don't strictly need the 0b at the front, but it can't hurt to add it.

Here's the loop from my first post, storing binary values as strings:

foo = [1,1,0,0,1,0,1,0]final_digits = []# Store blocks of 8 digits as strings in final_digitsfor i in range(0, len(foo), 8):    temp = "".join(str(j) for j in foo[i:i+8])    final_digits.append(temp)# Or, read the strings as binary numbers, and convert to base 10.for i in range(0, len(foo), 8):    temp = int("".join(str(j) for j in foo[i:i+8]), 2)    final_digits.append(temp)
A bit more in-depth info on what this is doing:
  • range(0, len(foo), 8) creates a range object, which has every eighth number between 0 and len(foo). So, 0, 8, 16, etc.
  • "".join(...) joins whatever strings of text are between the parentheses, putting whatever is before the .join() between each item. In this case, it's putting an empty string--""--between each one, so it just concatenates whatever values are inside the parentheses into a single string.
  • str(j) for j in foo[i:i+8] is Python's wonderful list comprehension syntax. It takes the value i, which is whatever number the for loop is currently using from the range() object (so, every eighth number from 0 to len(foo)), takes a slice of the list foo starting at that number and going forward eight more values, and converts each item into a string. Then it makes those all into a list. This is equivalent to
foo = [1, 1, 0, 0, ...]final digits = []for i in range(0, len(foo), 8):    temp1 = foo[i:i+8]    temp2 = ""                 # empty string    for k in temp1:        temp2.append(str(k))
  • int(..., 2) takes the resulting string of ones and zeros, interprets it as a base 2/binary number, and converts it into base 10.
You should use the int(..., 2) bit if you need to do actual math on these values, like multiplying and dividing. You can leave them as strings (i.e., not use int(..., 2)) if you just need to count how often they appear.

Not using int(..., 2) will give you a final_digits list that looks like ['11001100', '00100101', ...], while using int(..., 2) gives a final_digits list that looks like [203, 56, 48, ...].

Thanks that helps alot I didn't quite understand it before, thanks for you're time and thank you to the rest who tried to help. When I'm done I will post my work so you guys can see what I've been working on thanks again. :)

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6660296
Share on other sites

Link to post
Share on other sites

Thanks that helps alot I didn't quite understand it before, thanks for you're time and thank you to the rest who tried to help. When I'm done I will post my work so you guys can see what I've been working on thanks again. :)

No problem!  I remember getting a lot of help from people when I was learning Python, so I try to pass it along when I can.

 

And yeah, do post what you've been working on at some point.  It sounds interesting.

Link to comment
https://linustechtips.com/topic/497817-python-question/#findComment-6660948
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×