Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表理解中带浮点格式的f字符串_Python_String_List Comprehension_Python 3.6_Number Formatting - Fatal编程技术网

Python 列表理解中带浮点格式的f字符串

Python 列表理解中带浮点格式的f字符串,python,string,list-comprehension,python-3.6,number-formatting,Python,String,List Comprehension,Python 3.6,Number Formatting,python 3.6最近引入了字符串格式的[f'str']。我试图比较.format()和f'{expr}方法 f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... ' 我正在尝试使用f'{expr}方法复制上述内容: print(f'{[((x - 32) * (5/9)) for x in Fah

python 3.6最近引入了字符串格式的
[f'str']
。我试图比较
.format()
f'{expr}
方法

 f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '
我正在尝试使用
f'{expr}
方法复制上述内容:

print(f'{[((x - 32) * (5/9)) for x in Fahrenheit]}')  # This prints the float numbers without formatting 

# output: [0.0, 15.555555555555557, 38.88888888888889]
# need instead: ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']
f'str'
中格式化浮点可以实现:

n = 10

print(f'{n:.2f} Celsius') # prints 10.00 Celsius 
试图在列表中实现这一点:

print(f'{[((x - 32) * (5/9)) for x in Fahrenheit]:.2f}') # This will produce a TypeError: unsupported format string passed to list.__format__
是否可以使用
f'str'
使用
f'str>的
.format()
方法实现与上述相同的输出


多谢各位

您需要将f字串放在理解中:

[f'{((x - 32) * (5/9)):.2f} Celsius' for x in Fahrenheit]
# ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']

为什么你要在f字串里做列表理解?对于
.format()
版本,您没有这样做。看起来你知道怎么做,你只需要不把它搞砸。如果我在列表comp之外做,它不会相应地修改每个元素。我在试着看看什么类型的expr可以用在
f'str'
中。你是在列表之外做的。“不会相应地修改每个元素”意味着什么?我需要它像使用
.format()
一样迭代地修改列表中的每个元素,试图找出如何获取此输出
[0.0,15.55555555557,38.88888888888 9]
['0.00摄氏度','15.56摄氏度','38.89摄氏度']
f'str'
一起使用列表理解。再说一遍:你已经证明你已经知道怎么做了。
[f'{((x - 32) * (5/9)):.2f} Celsius' for x in Fahrenheit]
# ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']