python字符串能减吗_在python中减去两个字符串(Subtract two strings in python)
在python中減去兩個字符串(Subtract two strings in python)
我應該計算兩個不同列表的元素之間的差異。 這是我的代碼:
import operator
a = ['5', '35.1', 'FFD']
b = ['8.5', '11.3', 'AMM']
difference = [each[0] - each[1] for each in zip(b, a)]
print difference
我需要這個輸出:
ba = ['3.5',' - 23.8','AMM-FFD']
我收到以下錯誤:
不支持的操作數類型 - :'str'和'str'
我不想使用像numpy或pandas這樣的任何類
I should calculate the difference between elements two different list. This is my code :
import operator
a = ['5', '35.1', 'FFD']
b = ['8.5', '11.3', 'AMM']
difference = [each[0] - each[1] for each in zip(b, a)]
print difference
I need this output:
b-a = ['3.5','-23.8','AMM-FFD']
I receive the following error:
unsupported operand type(s) for -: 'str' and 'str'
I don't want to use any class like numpy or pandas
原文:https://stackoverflow.com/questions/40592194
2020-05-09 08:05
滿意答案
您需要將數字轉換為float ,如果元素無法轉換為數字,請在它們之間插入'-' 。
diffs = []
for i, j in zip(a, b):
try:
diffs.append(str(float(j) - float(i)))
except ValueError:
diffs.append('-'.join([j, i]))
>>> print(diffs)
['3.5', '-23.8', 'AMM-FFD']
由于python是強類型的(不要與靜態與動態混淆),如果遇到字符串之間的算術運算符,它就不會隱式地對字符串的數值解釋執行算術運算。 對于字符串,減號運算符沒有明顯的行為,因為存在明顯的加號行為(即連接)。 你希望它從第一個字符串中刪除第二個字符串的實例嗎? 如果是這樣,那么您可以使用更明確的str.replace方法。 或者,如果第一個字符串以第二個字符串結尾,您是否希望它從第一個字符串中刪除第二個字符串? 預期的行為并非100%明顯,因此python作者沒有包含對字符串的__sub__方法支持。
此外,您的代碼中未使用operator模塊,因此無需導入它。
You need to convert numbers to floats, and if the elements cannot be converted to numbers, insert a '-' between them.
diffs = []
for i, j in zip(a, b):
try:
diffs.append(str(float(j) - float(i)))
except ValueError:
diffs.append('-'.join([j, i]))
>>> print(diffs)
['3.5', '-23.8', 'AMM-FFD']
Since python is strongly typed (not to be confused with static vs. dynamic) it does not implicitly perform arithmetic on the numeric interpretation of strings if it encounters an arithmetic operator between strings. There is no obvious behavior of the minus operator with regard to strings the way there is an obvious behavior of plus (i.e., concatenate). Would you expect it to remove instances of the second string from the first string? If so, there's already a more explicit str.replace method you can use. Or would you expect it to remove the second string from the first only if the first string ends with the second string? The expected behavior isn't 100% obvious, so the python authors did not include __sub__ method support for strings.
Also, the operator module isn't used in your code, so no need to import it.
2016-11-14
相關問答
您可以將字符轉換為整數和異或: l = [ord(a) ^ ord(b) for a,b in zip(s1,s2)]
這是一個更新的函數,以防XOR導致您需要字符串: def sxor(s1,s2):
# convert strings to a list of character pair tuples
# go through each tuple, converting them to ASCII code (ord)
# perform exclusiv...
>>> a = "column_number"
>>> b = "_url1"
>>> x = 1234
>>> globals()[a + b] = x
>>> column_number_url1
1234
沒有多少帖子解釋如何做到這一點的原因是因為(你可能已經收集過)這不是一個好主意 。 我保證您的用例也不例外。 如果您沒有注意到, globals()本質上是全局變量的字典。 這意味著你應該一直使用字典;) >>> a = "column_number"
>>> b = "_url1"
>...
根據功能的位置,您可以使用以下其中一種: globals()[string1 + string2]()
locals()[string1 + string2]()
Depending on where the function is, you can use one of these: globals()[string1 + string2]()
locals()[string1 + string2]()
基本上, if test_string in list_of_strings的test_string,你想要idom。 看起來您不需要區分大小寫,所以您可能需要 if test_string.lower() in (s.lower() for s in list_of_strings)
在你的情況下: >>> originals = ['0430f244a18146a0815aa1dd4012db46', '0430f244a18146a0815aa1dd40 12db46', '59739CC...
實際上在標準庫中碰巧有這個功能: difflib.SequencMatcher.find_longest_match There actually happens to be a function for this in the standard library: difflib.SequencMatcher.find_longest_match
使用itertools.combinations_with_replacement獲取插入x s的索引: import itertools
str1 = "ABC"
lst = list(str1)
for n in range(len(str1)):
for idxs in itertools.combinations_with_replacement(range(len(str1)), n):
xs = lst[:]
for i in reversed...
查看文檔以獲取詳細信息,但是對于您的示例,您可以編寫 print("{l}{x}{r}".format(l=left, r=right, x=2*''))
Look in the docs for details, but for your example you could write print("{l}{x}{r}".format(l=left, r=right, x=2*''))
我認為轉換為內置整數類型的二進制和操作可能會比逐字符工作更快(因為Python的int是用C而不是Python編寫的)。 我建議你在輸入文件的每一行上工作,而不是一次完成數百萬字符的字符串。 二進制和操作不需要任何攜帶,因此單獨使用每一行都沒有問題。 為了避免笨拙的字符串操作將結果填充到正確的長度,您可以使用str.format方法將您的整數str.format轉換為正確長度的二進制字符串。 這是一個將輸出寫入新文件的實現: import itertools
with open(filename...
現在你只測試長度和第一個字符匹配。 for i, c in zip(problem, solution):
if i != c:
# that's the first set of chars, but we're already returning??
return False
if i == c or "#" == c:
# wildcard works here, but already would have failed e...
您需要將數字轉換為float ,如果元素無法轉換為數字,請在它們之間插入'-' 。 diffs = []
for i, j in zip(a, b):
try:
diffs.append(str(float(j) - float(i)))
except ValueError:
diffs.append('-'.join([j, i]))
>>> print(diffs)
['3.5', '-23.8', 'AMM-FFD']
由于python是強...
相關文章
比如“12344321我愛java”與“1我432愛2134ajav”被認為兩個字符串相等!
Python 字符串操作,字符串序列用于表示和存儲文本,python中字符串是不可變的,一旦聲明,不能
...
字符串的格式化 在python中也有類似于c中的printf()的格式輸出標記。在python中格式化
...
python2和python3的區別,1.性能 Py3.0運行 pystone benchmark的速
...
Python 編程語言具有很高的靈活性,它支持多種編程方法,包括過程化的、面向對象的和函數式的。但最重
...
好久沒有寫了,還不是近期剛過的期末考試和期中考試 最近因為一個微信公眾平臺大賽在學phthon 找了本
...
python的官網:http://www.python.org/ 有兩個版本,就像struts1和st
...
Python的文件類型 Python有三種文件類型,分別是源代碼文件、字節碼文件和優化代碼文件
源代
...
在python中, 去除了i > 0周圍的括號,去除了每個語句句尾的分號,還去除了表示塊的花括號。多出
...
總結
以上是生活随笔為你收集整理的python字符串能减吗_在python中减去两个字符串(Subtract two strings in python)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot异步注解_Sprin
- 下一篇: 我的世界光影mod怎么用_用“戏剧化”光