列表1中的数字在未使用count()的情况下出现在列表2中的次数

时间:2017-03-01 01:01:40

标签: list frequency

尝试编写此代码以查看列表1中的数字出现在列表2中的次数,可以使用嵌套for或while循环,但我想出了它不起作用。我不想使用计数。

list1 = [4,7,2]
list2 = [2,3,4,2,5,6,3,2,6,7,3,4]
def compare(list1, list2):
    freq = ([i for i in list1 if i == num])
    return
print('The number 4 occurs in list2', freq, 'times')
print('The number 7 occurs in list2', freq, 'times')
print('The number 2 occurs in list2', freq, 'times')

2 个答案:

答案 0 :(得分:0)

我不完全确定我理解这个问题,
但是这个代码似乎有效,但如果你需要它用于交互式程序,它可能会很慢 希望这有帮助!

Cannot read config file: /Users/cbickel1/dev/learning/webpack-demo/~/.eslintrc
Error: ENOENT: no such file or directory, open '/Users/cbickel1/dev/learning/webpack-demo/~/.eslintrc'
Referenced from: /Users/cbickel1/dev/learning/webpack-demo/.eslintrc
Error: Cannot read config file: /Users/cbickel1/dev/learning/webpack-demo/~/.eslintrc
Error: ENOENT: no such file or directory, open '/Users/cbickel1/dev/learning/webpack-demo/~/.eslintrc'
Referenced from: /Users/cbickel1/dev/learning/webpack-demo/.eslintrc
    at Object.fs.openSync (fs.js:558:18)
    at Object.fs.readFileSync (fs.js:468:33)
    at readFile (/Users/cbickel1/.nvm/versions/node/v7.4.0/lib/node_modules/eslint/lib/config/config-file.js:70:24)
    at loadLegacyConfigFile (/Users/cbickel1/.nvm/versions/node/v7.4.0/lib/node_modules/eslint/lib/config/config-file.js:142:44)
    at loadConfigFile (/Users/cbickel1/.nvm/versions/node/v7.4.0/lib/node_modules/eslint/lib/config/config-file.js:222:22)
    at load (/Users/cbickel1/.nvm/versions/node/v7.4.0/lib/node_modules/eslint/lib/config/config-file.js:505:18)
    at configExtends.reduceRight (/Users/cbickel1/.nvm/versions/node/v7.4.0/lib/node_modules/eslint/lib/config/config-file.js:391:36)
    at Array.reduceRight (native)
    at applyExtends (/Users/cbickel1/.nvm/versions/node/v7.4.0/lib/node_modules/eslint/lib/config/config-file.js:362:28)
    at Object.load (/Users/cbickel1/.nvm/versions/node/v7.4.0/lib/node_modules/eslint/lib/config/config-file.js:536:22)

答案 1 :(得分:0)

试试这个:

list1 = [4,7,2]
list2 = [2,3,4,2,5,6,3,2,6,7,3,4]
occurrences = [0,0,0]
for i in range(len(list1)):
    for j in list2:
        if list1[i] == j:
            occurrences[i]+=1
print occurrences