简体   繁体   English

Python初学者; 对于循环和拉链

[英]Beginner in Python; For Loops & Zips

So I'm a freshman comp sci major. 因此,我是一名大一新生。 I'm taking a class that teaches Python. 我正在上一门教Python的课程。 This is my assignment: 这是我的任务:

Create a function that takes a string and a list as parameters. 创建一个将字符串和列表作为参数的函数。 The string should contain the first ten letters of the alphabet and the list should contain the corresponding numbers for each letter. 该字符串应包含字母表的前十个字母,列表应包含每个字母的对应数字。 Zip the string and list into a list of tuples that pair each letter and number. 将字符串压缩并列出为将每个字母和数字配对的元组列表。 The function should then print the number and corresponding letter respectively on separate lines. 然后,该功能应在单独的行上分别打印数字和相应的字母。 Hint: Use the zip function and a loop! 提示:使用zip函数和循环!

This is what I have so far: 这是我到目前为止的内容:

def alpha(letter, number):
    letter = "abcdefghij"
    number = [1,2,3,4,5,6,7,8,9,10]
    return zip(letter, number)
print alpha(letter, number)

The problem I have is an error on line 5 that says 'letter' is not defined. 我的问题是第5行出现错误,提示未定义“字母”。 I feel like there should be a for loop but, I don't know how to incorporate it. 我觉得应该有一个for循环,但是,我不知道如何合并它。 Please help me. 请帮我。

zip works on iterables (strings and lists are both iterables), so you don't need a for loop to generate the pairs as zip is essentially doing that for loop for you. zip适用于可迭代对象(字符串和列表都是可迭代对象),因此您不需要for循环即可生成对,因为zip本质上就是为您完成了for循环。 It looks like you want a for loop to print the pairs however. 看起来您想要for循环来打印对。

Your code is a little bit confused, you'd generally want to define your variables outside of the function and make the function as generic as possible: 您的代码有些混乱,通常需要在函数之外定义变量,并使函数尽可能通用:

def alpha(letter, number):
    for pair in zip(letter, number):
        print pair[0], pair[1]

letter = "abcdefghij"
number = [1,2,3,4,5,6,7,8,9,10]
alpha(letter, number)

The error you are having is due to the scope of the variables. 您遇到的错误是由于变量的范围引起的。 You are defining letter and number inside of the function, so when you call alpha(letter,number) they have not been defined. 您正在函数内部定义letternumber ,因此当您调用alpha(letter,number)它们尚未定义。

For printing the result you could iterate the result of zip , as in the following example: 要打印结果,可以迭代zip的结果,如以下示例所示:

def alpha(letters, numbers):
    for c,n in zip(letters,numbers):
        print c,n

letters = "abcdefghij"
numbers = range(1,11)
alpha(letters, numbers)

Output: 输出:

a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM