假设我有一个列表[[1,2,3],[4,5,6]]
我如何转置它们,使它们成为:[[1, 4], [2, 5], [3, 6]]?
我必须使用该zip功能吗?该zip功能是最简单的方法吗?
def m_transpose(m):
trans = zip(m)
return trans
Run Code Online (Sandbox Code Playgroud) 对于这个程序,我试图让用户在文件中输入他/她想要的文本,并让程序计算存储在该文件中的单词总数.例如,如果我输入"嗨我喜欢吃蓝莓馅饼",该程序应该总共读7个单词.程序运行正常,直到我输入选项6,它会计算单词的数量.我总是得到这个错误:'str'对象没有属性'items'
#Prompt the user to enter a block of text.
done = False
textInput = ""
while(done == False):
nextInput= input()
if nextInput== "EOF":
break
else:
textInput += nextInput
#Prompt the user to select an option from the Text Analyzer Menu.
print("Welcome to the Text Analyzer Menu! Select an option by typing a number"
"\n1. shortest word"
"\n2. longest word"
"\n3. most common word"
"\n4. left-column secret message!"
"\n5. fifth-words secret message!"
"\n6. word count"
"\n7. quit")
#Set option to …Run Code Online (Sandbox Code Playgroud) 在总结两个方面我需要帮助.
假设我有[[0,1,2],[3,4,5]]作为我的维度,将这些数字相加将返回int 15.
def sum_dimensions(x):
x = []
answer = sum(x)
return int(x)
Run Code Online (Sandbox Code Playgroud)
指出我在代码中的错误是值得赞赏的.
我在这里要完成的是生成一个大小为nxn的矩阵.无论矩阵是什么,我都必须填写1从左上角到右下角以及0其他任何地方的数字.
def identity(m):
new_identity = []
old_identity = m
for i in range(len(old_identity)):
new_identity.append(old_list[1])
return new_identity
Run Code Online (Sandbox Code Playgroud)
例如,如果矩阵为3,则预期结果为:
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
Run Code Online (Sandbox Code Playgroud)
或者更容易想象:
[[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]
Run Code Online (Sandbox Code Playgroud) 我想创建一个2x3矩阵.(2行,3列)当我运行我的代码时,我在括号中得到矩阵,这是不正确的.
def fill_matrix(numrows, numcols, val):
matrix = [[val for i in range(numrows)] for j in range(numcols)]
return (numrows, numcols, val)
Run Code Online (Sandbox Code Playgroud)
如果我选择创建一个2x2矩阵并用1填充所有漏洞,我应该得到这个:[[1,1],[1,1]]
但我得到了这个:(2,2,1)
我想测试[[5,6],[7,8]]的2x2矩阵,看看它是否是正方形。
我运行我的代码,我应该得到True,但是我得到False ...
def square(sq):
for element in sq:
if element:
return False
return True
Run Code Online (Sandbox Code Playgroud) 蟒蛇
如何转换网格:
x,x
x,x
Run Code Online (Sandbox Code Playgroud)
到列表列表?:
[['x', 'x'], ['x', 'x']]
Run Code Online (Sandbox Code Playgroud) 假设我有2个向量[2,4,6,8]和[1,3,5].
如果我根据他们的索引组合数字,我希望[3,7,11]作为我的结果.如果一个向量的索引多于另一个向量,则它将在计算中被排除.(这就是为什么8不包括在这里).我的问题是如何组合2个向量而忽略额外的8,如上所示?我需要一个功能.
def v_add(num1, num2):
total = num1 + num2
return total
Run Code Online (Sandbox Code Playgroud) 假设我有清单
[[1,2,3], [4,5,6]]
Run Code Online (Sandbox Code Playgroud)
我想为每个元素添加5.
然后新的列表将[[6,7,8],[9,10,11]]作为答案.
def add(num, list):
Run Code Online (Sandbox Code Playgroud)