python - 从 0 和 1 的字符串创建一组字符串,其中只有两个字符被更改(python)
问题描述
假设我有以下字符串:'0000'
我想创建一组字符串,其中只有两个数字被更改(在这种情况下从 0 到 1)
例如从一个字符串'0000'
我会得到一个结果:{'0011', '0101', '0110', '1001', '1010', '1100'}
这是我的代码:
def shift_two(string):
shift_2 = set()
for i in range(len(string)):
if i == len(string) - 1:
break
str_temp = list(string)
if str_temp[i] == '1':
str_temp[i] = '0'
else:
str_temp[i] = '1'
#copy a string, because list is mutable
for j in range(i+1,len(string)):
copy_str = str_temp.copy()
if copy_str[j] == '1':
copy_str[j] = '0'
shift_2.add(''.join(copy_str))
else:
copy_str[j] = '1'
shift_2.add(''.join(copy_str))
return shift_2
但也许有更有效的方法(并且更具可读性)来完成这项任务?
解决方案
这是一个使用[Python 3.Docs] 的变体: itertools - 创建迭代器以进行高效循环的函数。
代码00.py:
#!/usr/bin/env python
import sys
import itertools as it
def replace(s, replacements):
if len(s) < len(replacements):
return s
base = s[:-len(replacements)] + "".join(replacements)
return sorted(set("".join(i) for i in it.permutations(base, len(base))))
def main(*argv):
s = "0000"
repls = ("1", "1")
l = list(replace(s, repls))
print(l)
if __name__ == "__main__":
print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
main(*sys.argv[1:])
print("\nDone.")
输出:
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q061258915]> "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe" code00.py Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] 64bit on win32 ['0011', '0101', '0110', '1001', '1010', '1100'] Done.
推荐阅读
- flutter - 颤振:如何从非 Firebase 源获取推送通知有效负载
- drools - 如何找到需要很长时间才能完成的规则
- python - 不想在 Python 中使用 isalnum() 删除“_”
- python - 有没有办法在做熊猫 groupby 时使用索引号来选择列?
- javascript - 在 React-Native 中编程时 Intelijj 不提示任何导入
- java - 使用 Java 从 .raw 卷文件中读取和索引数据
- reactjs - 如何传递通过 useRef 收集的数据,然后将其传递给不同的函数?
- php - exec("chmod +x $path; $path") 是做什么的?
- android - 使用 AppAuth 注册用户
- docker - 无法使用 `docker attach SSH 到 Docker 实例
`