我想做一个脚本。程序应该得到一些L包含值和自然数的列表N。
如果N>0,则列表的对象N向左移动步骤。
如果N<0,则列表的对象abs(N)向右移动。
如果N=0列表保持不变...
例如: 对于N=1和L=[1,2,3,4,5],输出为[2,3,4,5,1]。
对于相同的列表,N=-1输出是[5,1,2,3,4]
我实际上是使用collection.deque来做到的,但我只想用列表、for 循环和“if”来做到这一点。
我无法理解如何使对象移动。
l = input("enter list:")
N = input("enter number of rotations:")
import collections
d = collections.deque(l)
d.rotate(-N)
print d
Run Code Online (Sandbox Code Playgroud) 这是一个工作脚本我写建立一个dictionary由2名给出的列表:该i-th对象L1是key到value设在i-th的地方L2.
L1=[1,2,'a','b']
L2=[(22,'aa'),['x'],('3',),('s',3)]
d = {}
sizeL = len(L1)
for i in range(sizeL):
key = L1[i]
val = L2[i]
d[key] = val
print "Output:\n"
print "\nL1=",L1
print "L2=",L2
print "dictionary d = ",d
Run Code Online (Sandbox Code Playgroud)
我想以不同的方式尝试:使用dict函数.因此,我需要创建一个带有元组的列表.我不明白怎么做.这是我尝试的:
L1=[1,2,'a','b']
L2=[(22,'aa'),['x'],('3'),('s','3')]
L=[]
n=len(L1)
for i in range(n):
L.append(L1[i],L2[i])
d=dict(L)
print d
Run Code Online (Sandbox Code Playgroud)
当然我得到错误,因为错误使用append函数..
想知道如何创建这个"元组列表",一个可以被dict函数使用的列表.
谢谢!
我写了一个比较2个字符串的函数脚本,并告诉我们是否有相同的元音(种类和数字).
例如:
sameVowels('aabcefiok','xcexvcxaioa') should return `true`
Run Code Online (Sandbox Code Playgroud)
并sameVowels('aabcefiok','xcexvcxaioia')应该返回false
这是我基于列表的尝试.它不能很好地工作,我不知道为什么; 在这个具体的例子中,它返回true两者.
def sameVowels(s1, s2):
L1=[]
L2=[]
L_vowles=['a','e','i', 'o','u','A','E','I','O', 'U'] #dont know how to use str.upper/lower on lists...
for i in s1:
if i in L_vowles:
L1.append(i)
for i in s2:
if i in L_vowles:
L2.append(i)
for i in L1:
L1.count(i)
for i in L2:
L2.count(i)
return L1.count(i)== L2.count(i)
Run Code Online (Sandbox Code Playgroud)
如你所见,我创建了一些愚蠢的列表--L_vowels ......
我想过使用,sets但我认为它不会有用,因为我不能用它进行任何计数.
我的尝试怎么了?
dictionary?谢谢!
我不明白为什么输出是这样的,而不是1,3,1.
x = 1
def f():
global x
y = x
x = 2
return x + y
print x
print f()
print x
##output:
##
##1
##3
##2
Run Code Online (Sandbox Code Playgroud)
好吧,我理解'在'函数内部,global x告诉函数查看函数外部的x(x = 1).然后我们将这个x = 1放入y; 因此,y = 1.现在,local x是2,因此x + y = 2 + 1 = 3.
为什么最后print x收益2?为什么以及如何让舆论"选择"返回本地/全球x?这两个命令都在函数statemante之外.
谢谢!
我试图写一个函数,获得2个参数(实际上是2个字符串)并比较它们(忽略大小写的差异).例如:
cmr_func('House', 'HouSe')
true
cmr_func('Chair123', 'CHAIr123')
true
cmr_func('Mandy123', 'Mandy1234')
False.
Run Code Online (Sandbox Code Playgroud)
好吧,我尝试了一些东西,但它似乎非常愚蠢和糟糕的设计功能,无论如何不起作用.我想知道.我相信我需要使用一些内置str功能,但我不确定它们如何帮助我.
我想过in用一些循环来使用函数.但我不知道应该在什么样的对象上应用循环.
def str_comp(a,b):
for i in a:
i.lower()
for i in b:
i.lower()
if a == b:
print 'true'
else:
print 'false'
Run Code Online (Sandbox Code Playgroud)
任何暗示或想法都受到欢迎.谢谢 :)
我想编写一个脚本,获取4个数字并打印2个中间数字.
我试了一下,但效果不好:
a = (input('enter first num:'))
b = (input('enter second num:'))
c = (input('enter thirs num:'))
d = (input('enter forth num:'))
##a=float(a)
##b=float(b)
##c=float(c)
##d=float(d)
List=[a,b,c,d]
L=[]
for i in List:
if i >> min(List):
if i << max(List):
L.append(i)
print L
Run Code Online (Sandbox Code Playgroud)
我不确定问题是什么,因为输出列表不连贯,实际上取决于输入.
我想得到一个线索或想法如何解决这个问题(仅使用列表,for和if - 这是非程序员的基础课程)