Loop inside an f-string as a value for an embed - python

I have a tuple with some values and I want to send them in an embed. They're inside a dictionary like this
dict = {key: [(1, 2, 3), other values here], other key: [(1, 2, 3, 4, 5), other values here]}
Now some of the tuples here are of different lengths and it triggers me if I used a loop to add an embed field since discord doesn't allow the name parameter to be false or null yet. If I use a 0 width whitespace character, there's a big space that I'd rather not have. Tried using ternary operators but it didn't work. I also can't have this
for i in range(0, len(dict) - 1): pass
since the loop would've already came to an end before I could use it to index the tuple. I also tried doing
value = f'{tuple[i] for i in range(0, len(tuple) - 1)}'
but the bot return <generator object stats.<locals>.<genexpr> at 0x0000012E94AB3200> instead of the values inside the tuple.
Edit:
Thanks to the people who answered! It now works, thanks

tuple[i] for i in range(0, len(tuple) - 1)
Is a generator expression, it doesn't produce any values unless consumed by something like a loop or list()
You can use the equivalent list-comprehension instead:
f'{[tuple[i] for i in range(0, len(tuple) - 1)]}'
Or put the generator inside a list()
f'{list(tuple[i] for i in range(0, len(tuple) - 1))}'

Because your comprehension is not wrapped in [] it is technically a generator expression () (I think this would have worked in python 2.7 though), try this:
my_tuple = (1, 2, 3, 4)
f'{[my_tuple[i] for i in range(0, len(my_tuple) - 1)]}'
Output:
[1, 2, 3]
Also, there are no tuple comprehensions in python because tuples are immutable.

Related

Add value to tuple within list

How to add value to tuple within list
a = [[('one','1'),('two','2')],[('three','3')]]
b = [['I','II'],['III']]
I want it to turn out like
a = [[('one','1','I'),('two','2','II')],[('three','3','III')]]
I try to use append but it doesn't work
Thanks for any help.
Tuples are immutable, which means you can't change them once they've been made. See here: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences.
The only way to achieve what you want would be to either remake your list, or delete the elements and add the new versions in-place.
You could try something like this:
a = [(1, 'one'), (2, 'two'), (3, 'three')]
b = ["I", "II", "III"]
updated_a = [(*i, j) for i, j in zip(a, b)]
Where I've assumed you've typoed in your question, and that the list of numerals has this form instead.

remove spaces/commas from a variable to add to a string

I need it to look like
https://doorpasscode.kringlecastle.com/checkpass.php?i= (3333)&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c
instead it looks like
https://doorpasscode.kringlecastle.com/checkpass.php?i= (3, 3, 3, 3)&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c
Code:
for i in range(0, 4):
for j in range(0, 4):
for k in range(0, 4):
for l in range(0, 4):
trypass=(i,j,k,l)
#print(i,j,k,l, sep='')
print('https://doorpasscode.kringlecastle.com/checkpass.php?i= {}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(trypass).strip(','))
strip only strips from the beginning and end of the string, it doesn't strip the characters from the middle.
Your problem isn't really stripping, it's adding unnecessary junk in the first place by directly stringifying the tuple.
To fix both, convert trypass to a string up front with no joiner characters in the middle:
trypass = ''.join(map(str, (i,j,k,l)))
A side-note: You could shorten this a lot with itertools.product to turn four loops into one (no arrow shaped code), and avoid repeatedly stringifying by converting the range elements to str only once, directly generating trypass without the intermediate named variables:
from itertools import product
for trypass in map(''.join, product(map(str, range(0, 4)), repeat=4)):
print('https://doorpasscode.kringlecastle.com/checkpass.php?i= ({})&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(trypass).)
.format(trypass) will format the tuple as a string using the default tuple formatting rules, e.g. (3, 3, 3, 3). Instead you should explicitly tell it how to format the string, like:
.format(''.join(str(i) for i in trypass))
You have a tuple that you want to reduce to a string.
>>> trypass = (3,3,3,3)
>>> ''.join(str(i) for i in trypass)
'3333'
Or, since you know there are exactly 4 digits,
print('https://doorpasscode.kringlecastle.com/checkpass.php?i={}{}{}{}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(*trypass))
Or, just iterate over the 4-digit numbers directly. itertools.product can generate the tuples for you.
import itertools
for trypass in itertools.product("0123", repeat=4):
print('https://doorpasscode.kringlecastle.com/checkpass.php?i={}{}{}{}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(*trypass))

Python using braces inside list brackets

Im very new to Python and finding it very different to anything ive encountered before coming from the PHP realm.
Background:
Ive searched SO and learned that the differences between:
x = [] and x{} is that the brackets will create a list and the curly braces is for creating a series. What I could not find however is an explination for the following
Question
Why does this piece of code use braces inside a list with brackets like so:
context.modules[(stock, length)] = 0
Why the braces inside the list?
And then as a "bonus help" if I may why set it to 0 (although that's probably out of scope of question)
Fullcode:
context.modules = {}
for stock in context.stock_list:
for length in context.channels:
context.modules[(stock, length)] = 0
This is a dictionary, as you understand:
In [463]: dct = {'a' : 1}
In [464]: dct['a']
Out[464]: 1
It has one key-value entry. The key is a str type. strs are allowed to be keys for a dictionary because they can be hashed because they are immutable and their objects yield a unique, unchanging hash value which the dictionary uses to index the object for fast access.
Similarly, ints, floats, bools, basically anything that is immutable may be a key. This includes tuples, but not structures such as lists, sets and dicts.
Now, here's a tuple:
In [466]: x = (1, 2)
x can be used as the key in a dictionary.
In [469]: d = {x : 5}
In [470]: d
Out[470]: {(1, 2): 5}
To access the value associated with the tuple, you'd index with it:
In [471]: d[(1, 2)]
Out[471]: 5
This is the basic meaning behind that syntax you ask about. It is interesting to note that the parenthesis are optional:
In [472]: d[1, 2]
Out[472]: 5
This is because the parenthesis do not demarcate a tuple, but the comma , does.
Your context.modules is not a list, it's a python dictionary (map in most other languages)
So, when you're doing this:
context.modules[(stock, length)] = 0
You're basically creating a key, value pair in the dictionary, with key as a tuple of (stock, length) and value as 0.
Considering
stock = 2 and length = 5
your context.modules after the above assignment, will look like this:
>>> context.modules
{(2, 5): 0}

Inputting key words and their values on Python

I'm trying to create a list with words and integer values and put them in the list together. For example,
keywords:
rain,10
shine,5
python,10
great,1
Well i know how to put the words in a list, but not the values. So I did so far:
pyList = {'python', 'great, 'shine', rain}
So basically im trying to input the keywords and their values and store them in a list.
I agree with the other answers that a dictionary is the best way to accomplish this, but if you are looking strictly for a way to put these items in a list together, you may consider creating a list of tuples.
a_list = [("rain", 10), ("shine", 5), ("python", 10), ("great", 1)]
When you want to access this data:
print(a_list)
Will output: [('rain', 10), ('shine', 5), ('python', 10), ('great', 1)]
To access either item independently:
for x, y in a_list:
print(x)
Will output:
rain
shine
python
great
Of course x in the code above can be replaced with y to output the second part of the tuple instead.
A dictionary might be better than a list.
item_dict = {'rain': 10, 'shine': 5, 'python': 10, 'great': 1}
The following code
print(item_dict['rain'])
will output 10
If you don't care what numbers they have, but just want a different one for each then you can enumerate a list and turn that into a dictionary.
items = ['rain','shine','python','great']
items_dict = dict(enumerate(items))
This will give you a dictionary with the following values
{0: 'rain', 1: 'shine', 2: 'python', 3: 'great'}

Python List Comprehension Setting Local Variable

I am having trouble with list comprehension in Python
Basically I have code that looks like this
output = []
for i, num in enumerate(test):
loss_ = do something
test_ = do something else
output.append(sum(loss_*test_)/float(sum(loss_)))
How can I write this using list comprehension such as:
[sum(loss_*test_)/float(sum(loss_))) for i, num in enumerate(test)]
however I don't know how to assign the values of loss_ and test_
You can use a nested list comprehension to define those values:
output = [sum(loss_*test_)/float(sum(loss_))
for loss_, test_ in ((do something, do something else)
for i, num in enumerate(test))]
Of course, whether that's any more readable is another question.
As Yaroslav mentioned in the comments, list comprehensions don't allow you to save a value into a variable directly.
However it allows you to use functions.
I've made a very basic example (because the sample you provided is incomplete to test), but it should show how you can still execute code in a list comprehension.
def loss():
print "loss"
return 1
def test():
print "test"
return 5
output = [loss()*test() for i in range(10) ]
print output
which is this case will result in a list [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
I hope this somehow shows how you could end up with the behaviour that you were looking for.
ip_list = string.split(" ") # split the string to a list using space seperator
for i in range(len(ip_list)): # len(ip_list) returns the number of items in the list - 4
# range(4) resolved to 0, 1, 2, 3
if (i % 2 == 0): ip_list[i] += "-" # if i is even number - concatenate hyphen to the current IP string
else: ip_list[i] += "," # otherwize concatenate comma
print("".join(ip_list)[:-1]) # "".join(ip_list) - join the list back to a string
# [:-1] trim the last character of the result (the extra comma)

Categories